2016-08-02 97 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 –