You can customize the Serializer. The following code is using 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
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 the entity adds 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 I did not want to change the json customization, I think I could create a request class, I do not know if it would be 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);
}