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的解决方案,甚至还有更多选项……

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之类的工具.价值?

推荐答案

readValue()可以用于任何和所有类型,包括JsonNode.readTree()仅适用于JsonNode(树模型);并且是为了方便而添加的.

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.

Json相关问答推荐

JOLT将对象名作为新属性添加到主体中

从JSON格式提取数据时分隔通用名称

如何将加权边列表导出到JSON树?

使用JQ将JSON输出转换为CSV复杂 struct

交换键和数组值,将旧键转换为新数组值,使用 jq

如何修复通过在 tsconfig.json 文件中添加allowImportingTsExtensions引发的错误 TS5023?

将=分隔值文件转换为:json文件

将请求中的数据推送到数组中

使用基本身份验证通过 CURL 发布 JSON

如何使用 Newtonsoft.Json 反序列化 JSON 数组

Java的JSON字符串整洁/格式化程序

使用 JSON 的 javascript 深拷贝

将错误消息作为 JSON 对象发送

字符串的 Gson 数组到 JsonArray

C#扁平化json struct

Spring MVC:不反序列化 JSON 请求正文

如何创建 JSON 对象 Node.js

在 Webpack 中加载静态 JSON 文件

如何从 JSON 响应中提取单个值?

你如何在 Arrays of Arrays 上 OPENJSON