我有两个Dto:
1)ObjectDto
{
"id":Integer,
"model": TypeDto
}
2)TypeDto
{
"id": String,
"description": String
}
在我的控制器Java中,我有:
@RequestMapping(value = "/my/endpoint", method = RequestMethod.POST, produces = "application/json")
public void controllerMethod(@RequestBody ObjectDto reqDto) {
// something
}
这是ObjectDto:
public class ObjectDto {
private Integer id;
private TypeDto model;
public ObjectDto(){}
// getter and setter
}
public class TypeDto {
private Integer id;
private String description;
public TypeDto(){}
public TypeDto(Integer id){
this.id = id;
if(id == 1){
t.description = "Id is " + id;
}else{
t.description = "nothing";
}
}
// getter and setter
}
如果我通过POST Http呼叫收到:
{
id:0,
model:1
}
如何使用TypeD反序列化对象以正确构造函数?
结果将是:
{
id:0,
model:{
"id":1,
"description":"Id is 1"
}
}
答案 0 :(得分:0)
您可以为此使用自定义反序列化器:
@RequestMapping(value = "/my/endpoint", method = RequestMethod.POST, produces = "application/json")
public void controllerMethod(@RequestBody ObjectDto reqDto) {
// something
}
@JsonDeserialize(using = ObjectDtoDeserializer.class)
public class ObjectDto {
// ......
}
public class ObjectDtoDeserializer extends JsonDeserializer<ObjectDto> {
@Override
public ObjectDto deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
// use jp.getText() and jp.nextToken to navigate through the json
return something;
}
}