请参阅以下代码。我需要将数据列表序列化为 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"}]}
这都是正确的,我这里只有一个需要。我需要更改列表的“根”元素。现在有“ fooList ”作为根元素——我需要改变它。
我发现很少有关于这个主题的主题和帖子,但没有什么能完全符合我的要求。该解决方案必须保留将 JSON 反序列化回相应 java 类的可能性。