杰克逊的readValue和readTree:何时使用哪个? [英] readValue and readTree in Jackson: when to use which?
问题描述
我刚刚开始使用Jackson JSON库。杰克逊是一个非常强大的库,但它有一个非常广泛的API。很多事情可以通过多种方式完成。这使得很难在杰克逊找到自己的方式 - 如何知道什么是正确/最好的做事方式?
I'm just starting using the Jackson JSON library. Jackson is a very powerful library, but it has a terribly extensive API. A lot of things can be done in multiple ways. This makes it hard to find your way in Jackson - how to know what is the correct/best way of doing things?
为什么我会使用这个解决方案:
Why would I use this solution:
String json = "{\"a\":2, \"b\":\"a string\", \"c\": [6.7, 6, 5.6, 8.0]}";
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readValue(json, JsonNode.class);
if (node.isObject()) {
ObjectNode obj = mapper.convertValue(node, ObjectNode.class);
if (obj.has("a")) {
System.out.println("a=" + obj.get("a").asDouble());
}
}
通过这样的解决方案:
String json = "{\"a\":2, \"b\":\"a string\", \"c\": [6.7, 6, 5.6, 8.0]}";
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(json);
if (node.isObject()) {
ObjectNode obj = (ObjectNode) node;
if (obj.has("a")) {
System.out.println("a=" + obj.get("a").asDouble());
}
}
或者我使用JsonFactory和JsonParser遇到的解决方案可能还有更多的选择...
Or over solutions that I came across using JsonFactory and JsonParser and maybe even more options...
看来mapper.readValue是最通用的,可以在很多情况下使用:读取JsonNode,ObjectNode, ArrayNode,PoJo等等。那么为什么我要使用mapper.readTree?
It seems to mee that mapper.readValue is most generic and can be used in a lot of cases: read to JsonNode, ObjectNode, ArrayNode, PoJo, etc. So why would I want to use mapper.readTree?
将JsonNode转换为ObjectNode的最佳方法是什么?刚刚转换为ObjectNode?或者使用像mapper.convertValue这样的东西?
And what is the best way to convert a JsonNode to an ObjectNode? Just cast to ObjectNode? Or use something like mapper.convertValue?
推荐答案
readValue()可以用于任何和所有类型,包括 JsonNode
。 readTree()仅适用于 JsonNode
(树模型);并且是为了方便而添加的。
readValue() can be used for any and all types, including JsonNode
. readTree() only works for JsonNode
(tree model); and is added for convenience.
请注意,您永远不想使用您的第一个示例:它相当于将您的节点写为JSON,然后将其读回 - 只是施展它。
Note that you NEVER want to use your first example: it is equivalent to writing out your node as JSON, then reading it back -- just cast it.
这篇关于杰克逊的readValue和readTree:何时使用哪个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!