且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

杰克逊如何在不投射的情况下将JsonNode转换为ArrayNode?

更新时间:2023-11-24 20:57:58

是的,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).