![](/img/trans.png)
[英]Getting object of an annotation on method or constructor parameters in java
[英]Java Jackson annotation for constructor with parameters
我有兩個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"
}
}
您可以為此使用自定義解串器:
@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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.