杰克逊如何在不强制转换的情况下将 JsonNode 转换为 ArrayNode? [英] Jackson how to transform JsonNode to ArrayNode without casting?

查看:73
本文介绍了杰克逊如何在不强制转换的情况下将 JsonNode 转换为 ArrayNode?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将我的 JSON 库从 org.json 更改为 Jackson,并且我想迁移以下代码:

I am changing my JSON library from org.json to Jackson and I want to migrate the following code:

JSONObject datasets = readJSON(new URL(DATASETS));
JSONArray datasetArray =  datasets.getJSONArray("datasets");

现在在杰克逊,我有以下几点:

Now in Jackson I have the following:

ObjectMapper m = new ObjectMapper();
JsonNode datasets = m.readTree(new URL(DATASETS));      
ArrayNode datasetArray = (ArrayNode)datasets.get("datasets");

但是我不喜欢那里的演员阵容,是否有可能出现 ClassCastException?是否有与 org.json 中的 getJSONArray 等效的方法,以便在它不是数组的情况下进行适当的错误处理?

However I don't like the cast there, is there the possibility for a ClassCastException? Is there a method equivalent to getJSONArray in org.json so that I have proper error handling in case it isn't an array?

推荐答案

是的,Jackson 手动解析器设计与其他库有很大不同.特别是,您会注意到 JsonNode 具有大多数通常与来自其他 API 的数组节点相关联的功能.因此,您无需强制转换为 ArrayNode 即可使用.举个例子:

Yes, the Jackson manual parser design is quite different from other libraries. In particular, you will notice that JsonNode has most of the functions that you would typically associate with array nodes from other API's. As such, you do not need to cast to an ArrayNode to use. Here's an example:

JSON:

{
    "objects" : ["One", "Two", "Three"]
}

代码:

final String json = "{\"objects\" : [\"One\", \"Two\", \"Three\"]}";

final JsonNode arrNode = new ObjectMapper().readTree(json).get("objects");
if (arrNode.isArray()) {
    for (final JsonNode objNode : arrNode) {
        System.out.println(objNode);
    }
}

输出:

一个"
两个"
三"

"One"
"Two"
"Three"

注意使用 isArray 在迭代之前验证节点实际上是一个数组.如果您对自己的数据结构绝对有信心,则无需进行检查,但如果您需要它,则可以使用它(这与大多数其他 JSON 库没有什么不同).

Note the use of isArray to verify that the node is actually an array before iterating. The check is not necessary if you are absolutely confident in your datas structure, but its available should you need it (and this is no different from most other JSON libraries).

这篇关于杰克逊如何在不强制转换的情况下将 JsonNode 转换为 ArrayNode?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆