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

查看:81
本文介绍了杰克逊如何在不投射的情况下将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:

JSON:

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

代码:

Code:

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天全站免登陆