2012-12-02 25 views
1

請參閱以下代碼。我需要序列化JSON到陣列中的數據的列表:如何修改用Jackson序列化的JSON數組的根元素

FooEntity.java:

public class FooEntity { 

String foo; 
String bar; 

public String getFoo() { 
    return foo; 
} 

public void setFoo(String foo) { 
    this.foo = foo; 
} 

public String getBar() { 
    return bar; 
} 

public void setBar(String bar) { 
    this.bar = bar; 
} 
} 

FooList.java:

​​3210

在這裏,我創建FooEntities的列表,並將其序列化爲JSON :

public void fooListToJson() throws IOException { 
    FooList fooList = new FooList(); 

    FooEntity fooEntity1 = new FooEntity(); 
    fooEntity1.setBar("fooEntity1 bar value"); 
    fooEntity1.setFoo("fooEntity1 foo value"); 

    FooEntity fooEntity2 = new FooEntity(); 
    fooEntity2.setBar("fooEntity2 bar value"); 
    fooEntity2.setFoo("fooEntity2 foo value"); 

    fooList.add(fooEntity1); 
    fooList.add(fooEntity2); 

    ObjectMapper mapper = new ObjectMapper(); 
    StringWriter stringWriter = new StringWriter(); 
    final JsonGenerator jsonGenerator = mapper.getJsonFactory().createJsonGenerator(stringWriter); 

    mapper.writeValue(jsonGenerator, fooList); 

    System.out.println(stringWriter.toString()); 

所以輸出followting:

{"fooList":[{"foo":"fooEntity1 foo value","bar":"fooEntity1 bar value"},{"foo":"fooEntity2 foo value","bar":"fooEntity2 bar value"}]} 

這一切都是正確的,我在這裏只有一個需要。我需要更改列表的「根」元素。現在有「fooList」作爲根元素 - 我需要改變它。

我發現很少有線程和貼子給這個主題,但是沒有什麼東西完全符合我的需要。解決方案必須保持將JSON反序列化回相應的java類的可能性。

回答

1

是否@JsonRootName提供您所需要的?

+2

嗨!是的,它的工作原理。我已經嘗試過,但它需要更多的東西 - 爲ObjectMapper啓用WRAP_ROOT_VALUE,然後還包含數據的List的@JsonValue註釋,以扁平化序列化的JSON(http://stackoverflow.com/questions/13386930/爲什麼 - 犯規 - jsonunwrapped工作換列表)。 請參考這個要點:https://gist.github.com/4193797 – stibi

+0

FYI鏈接被破壞 – rekire

相關問題