0

I have two Dto:

1) ObjectDto

{
  "id":Integer,
  "model": TypeDto
}

2) TypeDto

{
  "id": String,
  "description": String
}

In my controller java I have:

@RequestMapping(value = "/my/endpoint", method = RequestMethod.POST, produces = "application/json")
public void controllerMethod(@RequestBody ObjectDto reqDto) {
    // something
}

And this is 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

}

If I received via POST Http call:

{
id:0,
model:1
}

How can I deserialize the object using the TypeDto correct constructor?

The result will be:

    {
      id:0,
      model:{
             "id":1,
             "description":"Id is 1"
      }
    }
michele
  • 26,348
  • 30
  • 111
  • 168
  • The if in the constructor does nothing, you may indicate why you want to use a specific constructor instead of the no arg – pdem Sep 05 '18 at 09:16
  • Here to use a constructor in Jacson (question duplication?) https://stackoverflow.com/questions/21920367/why-when-a-constructor-is-annotated-with-jsoncreator-its-arguments-must-be-ann – pdem Sep 05 '18 at 09:18

1 Answers1

0

You can use a custom deserializer for this:

@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;
    }
}
S.K.
  • 3,597
  • 2
  • 16
  • 31