0

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.

JPRLCol
  • 749
  • 11
  • 28
  • I think this is what you are looking for https://stackoverflow.com/questions/14362247/jackson-adding-extra-fields-to-an-object-in-serialization – JPRLCol Jan 31 '18 at 11:48

2 Answers2

0

You could add @JsonProperty for the area and also use @JsonIgnore for sideA and SideB. Please check Jackson :: adding extra fields to an object in serialization

JPRLCol
  • 749
  • 11
  • 28
  • I thought it can be used only for serialization, but not for deserialization, when i need to use the combination of 2 JSON parameters in some method. – Yevhenii S. Jan 31 '18 at 12:01
0

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'}
yvoytovych
  • 871
  • 4
  • 12