我遇到了一个问题,试图将List作为根节点,但似乎无法获得此信息。让我解释。假设我们有一个类“ TestClass”
class TestClass{ String propertyA; }
现在,在某些实用程序方法中,这就是我要做的
String utilityMethod(){ List<TestClass> list = someService.getList(); new ObjectMapper().writeValueAsString(list); }
我想以JSON格式获取的输出是
{"ListOfTestClasses":[{"propertyA":"propertyAValue"},{"propertyA":"someOtherPropertyValue"}]}
我尝试使用
objMapper.getSerializationConfig().set(Feature.WRAP_ROOT_VALUE, true);
但是,我似乎仍然做得不好。
现在,我只是创建一个Map<String,TestClass>,并编写该代码来实现我要执行的操作,该方法可以正常工作,但显然这是一个hack。有人可以帮我提供更优雅的解决方案吗?谢谢
Map<String,TestClass>
不幸的是,即使WRAP_ROOT_VALUE启用了该功能,您仍然需要额外的逻辑来控制序列化Java集合时生成的根名称(有关详细信息,请参阅此答案)。这给您提供以下选择:
WRAP_ROOT_VALUE
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类。