序列化嵌套对象json jackson

时间:2016-08-02 12:18:51

标签: java json serialization jackson objectmapper

我正在使用Jackson json库将我的POJO转换为json:

    public class A {
        public String name;
        public B b;
    }

    public class B {
        public Object representation;
        public String bar;
    }

我想将A的实例序列化为JSON。我将使用 Jackson 中的ObjectMapper课程:

objectMapperPropertiesBuilder.setSerializationFeature(SerializationFeature.WRAP_ROOT_VALUE);
objectMapperPropertiesBuilder.setAnnotationIntrospector(new CustomAnnotionIntrospector());

此处注释introspector选择根元素,因为所有这些都是带有@XmlRootElement@XmlType等注释的JAXB类:

例如:如果我设置Object表示:

    public class C {
        public BigInteger ste;
        public String cr;
    }

使用此代码,我的JSON将如下所示:

rootA: {
  "name": "MyExample",
  "b": {
    "rep": {
      "ste": 7,
      "cr": "C1"
    },
    "bar": "something"
  }
}

但我希望根元素也附加到我的嵌套Object。对象可以是任何自定义POJO。

所以在这种情况下,我希望在我的JSON转换中附加类C的根元素。所以:

rootA: {
  "name": "MyExample",
  "b": {
    "rep": {
      "rootC": {
        "ste": 7,
        "cr": "C1"
      }
    },
    "bar": "something"
  }
}

如何在JSON转换中添加嵌套对象的根元素?我指定的所有objectMapper属性都适用于class A。我是否必须编写自定义序列化程序以将某些属性应用于嵌套对象?

1 个答案:

答案 0 :(得分:1)

您可以使用自定义序列化程序。但是,实现所需内容的最简单方法是使用Map来包装C实例:

Map<String, Object> map = new HashMap<>();
map.put("rootC", c);

您的课程将如下:

@JsonRootName(value = "rootA")
public class A {
    public String name;
    public B b;
}
public class B {
    @JsonProperty("rep")
    public Object representation;
    public String bar;
}
public class C {
    public BigInteger ste;
    public String cr;
}

创建JSON的代码是:

A a = new A();
a.name = "MyExample";

B b = new B();
b.bar = "something";

C c = new C();
c.cr = "C1";
c.ste = new BigInteger("7");

a.b = b;

Map<String, Object> map = new HashMap<>();
map.put("rootC", c);
b.representation = map;

ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
mapper.enable(SerializationFeature.INDENT_OUTPUT);

String json = mapper.writeValueAsString(a);

生成的JSON将是:

{
  "rootA" : {
    "name" : "MyExample",
    "b" : {
      "rep" : {
        "rootC" : {
          "ste" : 7,
          "cr" : "C1"
        }
      },
      "bar" : "something"
    }
  }
}