如何在Java中访问JsonNode的JSON字段、数组和嵌套对象?
一个JsonNode是Jackson 的树模型,用于JSON,它可以将JSON读取到JsonNode实例中,并将JsonNode写入JSON。使用Jackson通过创建ObjectMapper实例并调用readValue()方法将JSON读取到JsonNode中。我们可以使用JsonNode类的get()方法访问字段、数组或嵌套对象。我们可以使用asText()方法返回有效的字符串表示形式,并使用JsonNode类的asInt()方法将节点的值转换为Java int。
在下面的示例中,我们可以访问JSON字段、数组和JsonNode的嵌套对象。
示例
import com.fasterxml.jackson.databind.*;
import java.io.*;
public class ParseJSONNodeTest {
public static void main(String args[]) {
String jsonStr = "{ \"name\" : \"Raja\", \"age\" : 30," +
" \"technologies\" : [\"Java\", \"Scala\", \"Python\"]," +
" \"nestedObject\" : { \"field\" : \"value\" } }";
ObjectMapper objectMapper = new ObjectMapper();
try {
JsonNode node = objectMapper.readValue(jsonStr, JsonNode.class);
JsonNode nameNode = node.get("name");
String name = nameNode.asText();
System.out.println(name);
JsonNode ageNode = node.get("age");
int age = ageNode.asInt();
System.out.println(age);
JsonNode array = node.get("technologies");
JsonNode jsonNode = array.get(1);
String techStr = jsonNode.asText();
System.out.println(techStr);
JsonNode child = node.get("nestedObject");
JsonNode childField = child.get("field");
String field = childField.asText();
System.out.println(field);
} catch (IOException e) {
e.printStackTrace();
}
}
}输出
Raja 30 Scala value
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP