如何修改与Jackson序列化的JSON数组的根元素

时间:2012-12-02 20:26:15

标签: 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:

public class FooList {
public List<FooEntity> fooList;

public FooList() {
    this.fooList = new ArrayList<FooEntity>();
}

public void add(FooEntity fooEntity) {
    this.fooList.add(fooEntity);
}

public List<FooEntity> getFooList() {
    return fooList;
}

public void setFooList(List<FooEntity> fooList) {
    this.fooList = fooList;
}
}

在这里,我创建了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());

所以输出结果如下:

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

这一切都是正确的,我这里只有一个需要。我需要改变&#34; root&#34;列表的元素。现在有&#34; fooList &#34;作为根元素 - 我需要改变它。

我找到了很少的帖子和帖子来讨论这个话题,但是没有任何东西对我来说完全符合我的要求。解决方案必须保持将JSON反序列化回相应的java类的可能性。

1 个答案:

答案 0 :(得分:1)

@ JsonRootName能提供您所需要的吗?