【问题标题】:Jackson: understand if source JSON is an array or an objectJackson:了解源 JSON 是数组还是对象
【发布时间】:2018-06-01 09:32:27
【问题描述】:
在 Jackson 库中解析 JSON 需要:
-
对于一个对象
MapType hashMapType = typeFactory.constructMapType(HashMap.class, String.class, Object.class);
Map<String, Object> receivedMessageObject = objectMapper.readValue(messageBody, hashMapType);
-
对象数组
Map[] receivedMessage = objectMapper.readValue(messageBody, HashMap[].class)
为了路由到正确的解析,检查 messageBody 中是否有数组或对象的最佳方法是什么?是否只是直接在 MessageBody 中检查数组令牌?
【问题讨论】:
标签:
java
json
jackson
deserialization
【解决方案1】:
如果您想知道您的输入是数组还是对象,您可以简单地使用readTree 方法。一个简单的例子:
ObjectMapper mapper = new ObjectMapper();
String json1 = "{\"key\": \"value\"}";
String json2 = "[\"key1\", \"key2\"]";
JsonNode tree1 = mapper.readTree(json1);
System.out.println(tree1.isArray());
System.out.println(tree1.isObject());
JsonNode tree2 = mapper.readTree(json2);
System.out.println(tree2.isArray());
System.out.println(tree2.isObject());
如果您希望能够反序列化为多种类型,请查看Polymorphic Deserialization
【解决方案2】:
一个选项就是将可能是数组的所有内容都视为数组。如果您的源 JSON 刚刚从 XML 自动转换或使用像 Jettison 这样的 XML 优先库创建,这通常是最方便的。
这是一个非常常见的用例,为此有一个 Jackson 开关:
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
然后,您可以将属性反序列化为集合类型,无论它是源 JSON 中的数组还是对象。
【解决方案3】:
这是我根据@ryanp 的回答所做的:
public class JsonDataHandler {
public List<MyBeanClass> createJsonObjectList(String jsonString) throws JsonMappingException, JsonProcessingException {
ObjectMapper objMapper = new ObjectMapper();
objMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
List<MyBeanClass> jsonObjectList = objMapper.readValue(jsonString, new TypeReference<List<MyBeanClass>>(){});
return jsonObjectList;
}
}