我将JSON库从org.json更改为Jackson,并希望迁移以下代码:

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");

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的数组 node 关联的函数.因此,您不需要强制转换到ArrayNode即可使用.下面是一个例子:

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);
    }
}

输出:

"一个"

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).

Json相关问答推荐

JOLT将扁平数组内其他字段的两个值相乘

基于两个条件替换扁平化的SON中的值

Jolt转换,如果任何字段为空,则将对象值设置为空

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

合并2个嵌套词典

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

正向闪烁后的微调值

使用 jq 和脚本 bash 映射两个 json

如何使用 serde_json 构建有状态的流式解析器?

将 JSON 字符串解析为 Kotlin Android 中的对象列表(MOSHI?)

嵌套 JSON 到 CSV(多级)

序列化为json时如何忽略空列表?

Spring MVC 4:application/json内容类型设置不正确

使用 Spring 和 JsonTypeInfo 注释将 JSON 反序列化为多态对象模型

使用 gson 反序列化对象的特定 JSON 字段

如何在 MVC4 中将 Json 字符串输出为 JsonResult?

带有方法参数的 WCF webHttpBinding 错误. 最多可以在没有包装元素的情况下序列化一个主体参数

从 JSON 到 JSONL 的 Python 转换

有没有一种快速的方法可以在文本编辑器中将 JavaScript 对象转换为有效的 JSON?

通过url获取json数据并在python中使用(simplejson)