简体   繁体   中英

Convert JSON to a Java object with a calculated field

I have this JSON object:

[
    {
      "field1": "xxxxx",
      "field2": "vvvvvv",
      "field3": "cccccc",
      "field4": "zzzzzzz"
    },
    {
      "field1": "aaaaa",
      "field2": "ssssss",
      "field3": "dddddd",
      "field4": "ffffff"
    }
]

I'm using FasterXML's Jackson library to deserialize this JSON to my class Foo . This one has this structure:

@JsonIgnoreProperties(ignoreUnknown = true)
public class Foo {
    private String id;

    @JsonProperty("field1")
    private String customField1;

    @JsonProperty("field2")
    private String customField2;

    @JsonProperty("field3")
    private String customField3;

    @JsonProperty("field4")
    private String customField4;
    ................
 }

I would like to calculate value of field id at deserialize time. This value is the result of concatenating customField4 with customField3 . Is possible to perform this kind of operation or do I need to pass this value into my JSON?

Ok guys, solution is to set a custom

@JsonDeserialize(using = EntityJsonDeserializerCustom.class)

in this way I've created a generic static class with only fields returned by json an then I override deserialize method to return me my object with calculated field

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonDeserialize(using = EntityJsonDeserializerCustom.class)
public class Foo {


    private String id;

    @JsonProperty("field1")
    private String customField1;

    @JsonProperty("field2")
    private String customField2;

    @JsonProperty("field3")
    private String customField3;

    @JsonProperty("field4")
    private String customField4;
    ................
 }


public class EntityJsonDeserializerCustom extends JsonDeserializer<Foo> {

    @Override
    public Foo deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {

        InnerFoo innerFoo = jp.readValueAs(InnerFoo.class);

        Foo foo = new Foo();
        foo.setField1(innerFoo.field1);
        foo.setField2(innerFoo.field2);
        foo.setField3(innerFoo.field3);
        foo.setField4(innerFoo.field4);
        foo.setId(innerFoo.field4 + innerFoo.field3);


        return foo;
    }

    @JsonIgnoreProperties(ignoreUnknown = true)
    public static class InnerFoo {
        @JsonProperty("field1")
        private String customField1;

        @JsonProperty("field2")
        private String customField2;

        @JsonProperty("field3")
        private String customField3;

        @JsonProperty("field3")
        private String customField4;
    }
}

In this way I solve my problem, I hope this is helpfully for community :D

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM