不幸的是,即使
WRAP_ROOT_VALUE启用了该功能,您仍然需要额外的逻辑来控制序列化Java集合时生成的根名称(有关详细信息,请参阅此答案)。这给您提供以下选择:
- 使用Holder类定义根名称
- 使用地图。
- 使用自定义
ObjectWriter
以下代码说明了三个不同的选项:
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“}]}
使用an
ObjectWriter非常方便-只需记住,使用它序列化的所有顶级对象都将具有相同的根名。如果那不是理想的,则使用map或holder类。



