不幸的是,即使WRAP_ROOT_VALUE
启用了该功能,您仍然需要额外的逻辑来控制在序列化 Java 集合时生成的根名称(有关详细信息,请参阅此答案)。这让您有以下选择:
这是一些说明三个不同选项的代码:
public class TestClass {
private String propertyA;
// constructor/getters/setters
}
public class TestClassListHolder {
@JsonProperty("ListOfTestClasses")
private List<TestClass> data;
// constructor/getters/setters
}
public class TestHarness {
protected List<TestClass> getTestList() {
return Arrays.asList(new TestClass("propertyAValue"), new TestClass(
"someOtherPropertyValue"));
}
@Test
public void testSerializeTestClassListDirectly() throws Exception {
final ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
System.out.println(mapper.writeValueAsString(getTestList()));
}
@Test
public void testSerializeTestClassListViaMap() throws Exception {
final ObjectMapper mapper = new ObjectMapper();
final Map<String, List<TestClass>> dataMap = new HashMap<String, List<TestClass>>(
4);
dataMap.put("ListOfTestClasses", getTestList());
System.out.println(mapper.writeValueAsString(dataMap));
}
@Test
public void testSerializeTestClassListViaHolder() throws Exception {
final ObjectMapper mapper = new ObjectMapper();
final TestClassListHolder holder = new TestClassListHolder();
holder.setData(getTestList());
System.out.println(mapper.writeValueAsString(holder));
}
@Test
public void testSerializeTestClassListViaWriter() throws Exception {
final ObjectMapper mapper = new ObjectMapper();
final ObjectWriter writer = mapper.writer().withRootName(
"ListOfTestClasses");
System.out.println(writer.writeValueAsString(getTestList()));
}
}
输出:
{"ArrayList":[{"propertyA":"propertyAValue"},{"propertyA":"someOtherPropertyValue"}]}
{"ListOfTestClasses":[{"propertyA":"propertyAValue"},{"propertyA":"someOtherPropertyValue "}]}
{"ListOfTestClasses":[{"propertyA":"propertyAValue"},{"propertyA":"someOtherPropertyValue"}]}
{"ListOfTestClasses":[{"propertyA":"propertyAValue"},{"propertyA ":"someOtherPropertyValue"}]}
使用 anObjectWriter
非常方便 - 请记住,使用它序列化的所有顶级对象都将具有相同的根名称。如果那不是可取的,那么请改用地图或持有人类。