2016-08-02 42 views
2

我使用JSON杰克逊库,我的POJO转换成JSON:序列化嵌套对象JSON杰克逊

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

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

我想序列的A一个实例为JSON。我将使用ObjectMapper类从Jackson

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

这里注释内省挑选根元素,因为所有这些都是JAXB类与注释像@XmlRootElement@XmlType

例如:如果我在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。我是否必须编写自定义序列化程序以将某些属性应用于嵌套对象?

+0

请注意,您在问题中提供的JSON无效。你可以验证他们[这里](http://jsonlint.com/)。 –

回答

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" 
    } 
    } 
} 
+0

这可行,但设置输入不在我的手中。我得到一个对象填充,我不得不序列化它,所以我不是一个设置'地图'(客户端这样做)。所以我应该去自定义序列化程序? –

+0

如果我使用自定义序列化器,我只想使用自定义方式将“representation”部分序列化,然后使用我在Root类中设置的ObjectMapper属性对所有属性进行序列化。这怎么能实现? –

+0

另外,我的POJO也不能编辑注释。将不得不使用ObjectMapper –