在将JSON反序列化为Java对象时,如何将父属性映射到子对象?

时间:2014-04-02 02:40:29

标签: java json serialization jackson deserialization

给出这样的JSON:

{
    "locale" : "US",
    "children" : [
            {
                "foo" : "bar"
            },
            {
                "foo" : "baz"
            }
        ]
}

映射到Java对象,如下所示:

public class Parent {
    @JsonProperty public String getLocale() {...}
    @JsonProperty public List<Child> getChildren() {...}
}

public class Child {
    public void setLocale(String locale) {...}
    @JsonProperty public String getFoo() {...}
}

如何使用顶部(Parent)级别的JSON中的值填充Child实例的locale属性?

我以为我可以在@JsonDeserialize(using=MyDeserializer.class)的{​​{1}}方法上使用setLocale()来使用自定义序列化程序,但这不起作用(我怀疑是因为没有值在Child级别的JSON,因此Jackson不知道任何应该反序列化到Child属性中的值。)

我想避免为整个locale类编写一个完整的自定义反序列化器,实际上有更多的数据需要映射。

1 个答案:

答案 0 :(得分:1)

如果可以在子对象中引用父对象,则可以使用bi-directional references在类之间建立父子关系。这是一个例子:

public class JacksonParentChild {
    public static class Parent {
        public String locale;
        @JsonManagedReference
        public List<Child> children;

        @Override
        public String toString() {
            return "Parent{" +
                    "locale='" + locale + '\'' +
                    ", children=" + children +
                    '}';
        }
    }

    public static class Child {
        @JsonBackReference
        public Parent parent;
        public String foo;

        @Override
        public String toString() {
            return "Child{" +
                    "locale='" + parent.locale + '\'' +
                    ", foo='" + foo + '\'' +
                    '}';
        }
    }

    final static String json = "{\n" +
            "    \"locale\" : \"US\",\n" +
            "    \"children\" : [\n" +
            "            {\n" +
            "                \"foo\" : \"bar\"\n" +
            "            },\n" +
            "            {\n" +
            "                \"foo\" : \"baz\"\n" +
            "            }\n" +
            "        ]\n" +
            "}";

    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        Parent parent = mapper.readValue(json, Parent.class);
        System.out.println("Dumping the object");
        System.out.println(parent);
        System.out.println("Serializing to JSON");
        System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(parent));
    }
}

输出:

Dumping the object:
Parent{locale='US', children=[Child{locale='US', foo='bar'}, Child{locale='US', foo='baz'}]}
Serializing to JSON:
{
  "locale" : "US",
  "children" : [ {
    "foo" : "bar"
  }, {
    "foo" : "baz"
  } ]
}