将JSON转换为具有计算字段

时间:2016-02-03 17:14:27

标签: java json serialization jackson fasterxml

我有这个JSON对象:

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

我正在使用FasterXML的Jackson库将此JSON反序列化到我的班级Foo。这个有这个结构:

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

我想在反序列化时计算字段id的值。此值是将customField4customField3连接起来的结果。是可以执行这种操作还是我需要将此值传递给我的JSON?

1 个答案:

答案 0 :(得分:0)

好的家伙,解决方案是设置自定义

@JsonDeserialize(using = EntityJsonDeserializerCustom.class)

通过这种方式,我创建了一个只有json返回的字段的通用静态类,然后我覆盖了deserialize方法,用计算字段返回我的对象​​

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

通过这种方式我解决了我的问题,我希望这对社区有用:D