json 的解析包:
com.fasterxml.jackson.core
jackson-core
2.9.6
com.fasterxml.jackson.core
jackson-annotations
2.9.6
com.fasterxml.jackson.core
jackson-databind
2.9.6
Jackson的基本应用:
JsonNode 类是 Jackson 的一个将 Json 内容反序列到内存的一种内存数据结构表达方式。
例如对于一个测试的Json内容:
{
"name" : "test",
"value" : 20,
"address" : [
{
"addressId" : "0001"
},
{
"addressId" : "0002"
}
]
}
当我们把json内容反序列化到内存中的时候,便可以如同操作一个树结构读取json内容:
String name = node.get("name").asText();
Integer value = node.get("value").asInt();
Iterator addressNodes = node.get("address").elements();
String address = addressNodes.next().get("addressId").asText();
从上我们可以发现, jackson 可以方便的进行节点定位跟类型转换。
如何才能将json内容转换成 JsonNode 呢 ?
文件字符串解析
public static JsonNode str2JsonNode(String str) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readTree(str);
}
stream 解析
public static JsonNode str2JsonNode(InputStream stream) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readTree(stream);
}
file 解析
public static JsonNode str2JsonNode(File file) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readTree(file);
}
reader 解析
public static JsonNode str2JsonNode(Reader reader) throws IOException {
ObjectMapper objectMapp