Java Джексон аннотация для конструктора с параметрами - PullRequest
0 голосов
/ 05 сентября 2018

У меня есть два 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
}

Как я могу десериализовать объект, используя правильный конструктор TypeDto?

Результат будет:

    {
      id:0,
      model:{
             "id":1,
             "description":"Id is 1"
      }
    }

1 Ответ

0 голосов
/ 05 сентября 2018

Для этого вы можете использовать специальный десериализатор:

@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;
    }
}
...