140

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

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?

4

5 回答 5

282

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

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

输出:

“一”
“二”
“三”

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

于 2013-05-28T13:18:39.123 回答
16

在 Java 8 中,您可以这样做:

import java.util.*;
import java.util.stream.*;

List<JsonNode> datasets = StreamSupport
    .stream(obj.get("datasets").spliterator(), false)
    .collect(Collectors.toList())
于 2020-05-07T13:15:34.723 回答
5

我假设在一天结束时您想通过迭代来使用 ArrayNode 中的数据。为了那个原因:

Iterator<JsonNode> iterator = datasets.withArray("datasets").elements();
while (iterator.hasNext()) 
        System.out.print(iterator.next().toString() + " "); 

或者如果您喜欢流和 lambda 函数:

import com.google.common.collect.Streams;
Streams.stream(datasets.withArray("datasets").elements())
    .forEach( item -> System.out.print(item.toString()) )
于 2018-11-30T14:15:31.017 回答
1

org.json 中是否有与 getJSONArray 等效的方法,以便在它不是数组的情况下进行适当的错误处理?

这取决于您的输入;即您从 URL 中获取的内容。如果“datasets”属性的值是关联数组而不是普通数组,您将获得一个ClassCastException.

但是话又说回来,旧版本的正确性取决于输入。在你的新版本抛出 a 的情况下ClassCastException,旧版本会抛出JSONException. 参考:http://www.json.org/javadoc/org/json/JSONObject.html#getJSONArray(java.lang.String)

于 2013-05-28T09:20:50.247 回答
0

通过调用JsonNode的iterator()方法获取一个迭代器,然后继续……

  JsonNode array = datasets.get("datasets");

  if (array.isArray()) {
      Iterator<JsonNode> itr = array.iterator();
      /* Set up a loop that makes a call to hasNext().
      Have the loop iterate as long as hasNext() returns true.*/
      while (itr.hasNext()) {
          JsonNode item=itr.next();
          // do something with array elements
      }
  }
于 2022-03-03T12:19:27.087 回答