Custom Json Spring Receipt

Asked

Viewed 1,300 times

1

Hey, guys. All right?

Currently in my system I am mapping the objects in a Spring standard way, but I would like to do a custom mapping:

Current controller

@RequestMapping(value = "", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Bloquete> create(@RequestBody Bloquete obj) {
    Bloquete objAtualizado = repository.save(obj);
    return new ResponseEntity<Bloquete>(objAtualizado, HttpStatus.CREATED);
}

Current request

{
    "cedente":{"id":40,"nome":"Empresa","documentoIdentificacao":"06789233133"},
    "contaBancaria":{"id":14,"agencia":"0400","conta":"9424283"},
}

Desired request

{
    "cedente":40,
    "contaBancaria":14,
}

Current and desired response

{
    "id":17382173
    "cedente":{"id":40,"nome":"Empresa","documentoIdentificacao":"06789233133"},
    "contaBancaria":{"id":14,"agencia":"0400","conta":"9424283"},
}

Completion

The idea is that who is sending the request nay have to have object information only your id but without doing so:

{
    "cedente":{"id":40},
    "contaBancaria":{"id":14},
}

Thanks in advance.

1 answer

2


You can customize the Serializer . The code below uses the api Jackson Json:

import java.io.IOException;
    import com.fasterxml.jackson.core.JsonGenerator;
    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.databind.JsonSerializer;
    import com.fasterxml.jackson.databind.SerializerProvider;
    public class BloqueteSerializer extends JsonSerializer<Bloquete> {
      @Override
      public void serialize(Bloquete bloquete, JsonGenerator jG, SerializerProvider arg2) throws IOException,JsonProcessingException {
        jG.writeStartObject();
        jG.writeNumberField("cedente", bloquete.getCedente().getId());
        jG.writeNumberField("contaBancaria", bloquete.getContaBancaria().getId());
        jG.writeEndObject();
      }
    }

and deserialize him

import java.io.IOException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
public class BloqueteDeserialize extends JsonDeserializer<Bloquete>{
    @Override
    public Bloquete deserialize(JsonParser jp, DeserializationContext arg1)
            throws IOException, JsonProcessingException {
        JsonNode node = jp.readValueAsTree();
        Bloquete bloquete = new Bloquete();
        bloquete.setCedente(new Cedente); 
        bloquete.getCedente.setId(node.get("cedente").asInt())
        bloquete.setContaBancaria(new ContaBancaria);
        bloquete.getcontaBancaria.setId(node.get("contaBancaria"));
        return bloquete;
    }
}    

and in the entity adds the annotations:

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@JsonDeserialize(using = BloqueteDeserialize.class)
@JsonSerialize(using = BloqueteSerializer.class)
public class Bloquete {

}

if you didn’t want to change the json customization, I think you could create a request class, I don’t know if it would be a good practice to do this.

public class BloqueteRequest{
      private int cedente;
      private int contaBancaria;
  }

and in the method would fill this class

@RequestMapping(value = "", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
  public ResponseEntity<?> create(@RequestBody Bloquete obj) {
      Bloquete objAtualizado = repository.save(obj);

      BloqueteRequest br = new BloqueteRequest();
      br.setCedente(objAtualizado.getCedente.getId());
      br.setContaBancaria(objAtualizado.getContaBancaria.getid());


      return new ResponseEntity<BloqueteRequest>(br, HttpStatus.CREATED);
  }
  • I want to send "assignor":1 and receive "assignor":{id:1,...}. I believe in his example he does the opposite. of this

  • updated the response

  • I’ve already marked your answer as the correct one, because that’s really what I want. But I’m having trouble making the request. You’re always making the mistake. Quando busco os bloquetes dá "fasterxml.jackson.databind.JsonMappingException" e quando tento criar um bloquete dá "Failed to write HTTP message: org.springframework.http.converter.HttpMessageNotWritableException". Any suggestions?

  • implements only Jsonserialize. vc returns the object in another Answer? vc already used Jackson json?

  • I posted another question with what’s going on. http://answall.com/questions/138346/spring-jackson-json-problema-no-deserialize

Browser other questions tagged

You are not signed in. Login or sign up in order to post.