Search code examples
javajsonjacksonjson-deserialization

How to deserialize some JSON parameters as one new variable in DTO


How to deserialize JSON (using Jackson) into Java object if some JSON parameters should be used to create variable of Java DTO(but not be deserialized as dto variables).

For example I have JSON {"sideA" : 2, "sideB" : 4, "useless_parameter" : "useless_information"} and I need to get result of toString (of deserialized Java object) something like : RectangleDto{area = 8, useless_parameter = "useless_information"}

If I need to deserialize "useless_parameter" then I can use @JsonGetter("useless_information"), so what should I do with "sideA" and "sideB" if I need to take area as variable of RectangleDto? I already have a method for conversion JSON parameters into this variable.


Solution

  • Probably you need a custom deserializer:

    class MyDeserializer extends StdDeserializer<RectangleDto> {
    
        public MyDeserializer() {
            this(null);
        }
    
        protected MyDeserializer(Class<?> vc) {
            super(vc);
        }
    
        @Override
        public RectangleDto deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
            JsonNode node = jp.getCodec().readTree(jp);
            int a = node.get("sideA").intValue();
            int b = node.get("sideB").intValue();
            String useless_parameter = node.get("useless_parameter").asText();
    
            RectangleDto test = new RectangleDto();
            test.setArea(a * b);
            test.setUseless_parameter(useless_parameter);
    
            return test;
        }
    }
    

    Then register the deserializer on the class

    @JsonDeserialize(using = MyDeserializer.class)
    public class RectangleDto {
    
        private int area;
        private String useless_parameter;
        // getters, setters...
    }
    

    Then this will work as you want:

    RectangleDto r = mapper.readValue("{\"sideA\" : 2, \"sideB\" : 4, \"useless_parameter\" : \"useless_information\"}", RectangleDto.class);
    System.out.println(r);
    

    results in

    RectangleDto{area=8, useless_parameter='useless_information'}