转换杰克逊的正确方法是什么JsonNode
到java集合?
如果它是一个 json 字符串我可以使用ObjectMapper.readValue(String, TypeReference)
但对于一个JsonNode
唯一的选择是ObjectMapper.treeToValue(TreeNode, Class)
这不会给出类型化的集合,或者ObjectMapper.convertValue(Object, JavaType)
由于它接受任何 POJO 进行转换,所以感觉不对。
还有另一种“正确”的方法还是其中之一?
获得一个ObjectReader https://fasterxml.github.io/jackson-databind/javadoc/2.7/com/fasterxml/jackson/databind/ObjectReader.html with ObjectMapper#readerFor(TypeReference) https://fasterxml.github.io/jackson-databind/javadoc/2.7/com/fasterxml/jackson/databind/ObjectMapper.html#readerFor(com.fasterxml.jackson.core.type.TypeReference)用一个TypeReference http://fasterxml.github.io/jackson-core/javadoc/2.7/com/fasterxml/jackson/core/type/TypeReference.html?is-external=true描述您想要的类型化集合。然后使用ObjectReader#readValue(JsonNode) https://fasterxml.github.io/jackson-databind/javadoc/2.7/com/fasterxml/jackson/databind/ObjectReader.html#readValue(com.fasterxml.jackson.databind.JsonNode)来解析JsonNode https://fasterxml.github.io/jackson-databind/javadoc/2.7/com/fasterxml/jackson/databind/JsonNode.html(大概是一个ArrayNode https://fasterxml.github.io/jackson-databind/javadoc/2.7/com/fasterxml/jackson/databind/node/ArrayNode.html).
例如,要获得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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)