Java Jackson JsonNode 到类型集合
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39237835/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hymanson JsonNode to typed Collection
提问by kag0
What is the proper way to convert a Hymanson JsonNode
to a java collection?
将 Hymanson 转换JsonNode
为 Java 集合的正确方法是什么?
If it were a json string I could use ObjectMapper.readValue(String, TypeReference)
but for a JsonNode
the only options are ObjectMapper.treeToValue(TreeNode, Class)
which wouldn't give a typed collection, or ObjectMapper.convertValue(Object, JavaType)
which feels wrong on account of its accepting any POJO for conversion.
如果它是一个 json 字符串,我可以使用,ObjectMapper.readValue(String, TypeReference)
但JsonNode
唯一的选项是ObjectMapper.treeToValue(TreeNode, Class)
不提供类型化集合,或者ObjectMapper.convertValue(Object, JavaType)
由于接受任何 POJO 进行转换而感觉错误。
Is there another "correct" way or is it one of these?
还有另一种“正确”的方式还是其中一种?
采纳答案by Sotirios Delimanolis
Acquire an ObjectReader
with ObjectMapper#readerFor(TypeReference)
using a TypeReference
describing the typed collection you want. Then use ObjectReader#readValue(JsonNode)
to parse the JsonNode
(presumably an ArrayNode
).
获取ObjectReader
与ObjectMapper#readerFor(TypeReference)
使用TypeReference
描述你想要的类型集合。然后用于ObjectReader#readValue(JsonNode)
解析JsonNode
(大概是一个ArrayNode
)。
For example, to get a List<String>
out of a JSON array containing only JSON strings
例如,List<String>
从仅包含 JSON 字符串的 JSON 数组中获取
ObjectMapper mapper = new ObjectMapper();
// example JsonNode
JsonNode arrayNode = mapper.createArrayNode().add("one").add("two");
// acquire reader for the right type
ObjectReader reader = mapper.readerFor(new TypeReference<List<String>>() {
});
// use it
List<String> list = reader.readValue(arrayNode);
回答by DanJ
The ObjectMapper.convertValue()function is convenient and type-aware. It can perform a wide array of conversions between tree nodes and Java types/collections, and vice-versa.
该ObjectMapper.convertValue()函数是方便和感知类型。它可以在树节点和 Java 类型/集合之间执行广泛的转换,反之亦然。
An example of how you might use it:
您可能如何使用它的示例:
List<String> list = new ArrayList<>();
list.add("one");
list.add("two");
Map<String,List<String>> hashMap = new HashMap<>();
hashMap.put("myList", list);
ObjectMapper mapper = new ObjectMapper();
ObjectNode objectNode = mapper.convertValue(hashMap, ObjectNode.class);
Map<String,List<String>> hashMap2 = mapper.convertValue(objectNode, HashMap.class);