JsonNode、ObjectNode和ArrayNode

我个人不喜欢fastjson,但是项目中很多地方用到json字符串转换对象但又不想创建pojo
所以使用jackson的JsonNode、ObjectNode和ArrayNode就非常好用,万能对象,这三
个对象是非常全面的,感兴趣的可以看下源码

JsonNode 只读,通常由ObjectMapper解析json字符串得到
ObjectNode 可修改, 继承JsonNode
ArrayNode 可修改, 继承JsonNode

ObjectNode类似fastjson的JSONObject
ArrayNode类似fastjson的JSONArray

ObjectNode objectNode0 = JsonNodeFactory.instance.objectNode();  
objectNode0.put("sub", "child");  
  
ObjectNode objectNode = JsonNodeFactory.instance.objectNode();  
objectNode.put("aa","aa");  
objectNode.put("a1",111);  
objectNode.put("a2","123");  
objectNode.put("a4",true);  
objectNode.put("a5",objectNode0);  
System.out.println(objectNode);  
  
ArrayNode arrayNode = JsonNodeFactory.instance.arrayNode();  
arrayNode.add(123);  
arrayNode.add("abd");  
arrayNode.add(true);  
arrayNode.add(objectNode0);  
System.out.println(arrayNode);

// JsonNode 
String json = "{\n" +  
    "    \"id\": \"AaEXKZGjdBAQVxtqofPymQmJhuuuupGD\",\n" +  
    "    \"roleName\": \"临时角色uuuu\",\n" +  
    "    \"roleCode\": \"test20uuuu33120\",\n" +  
    "    \"description\": \"这是新建的临时角色123\",\n" +  
    "    \"createBy\": \"admin\",\n" +  
    "    \"createTime\": \"2023-09-10 19:57:26\",\n" +  
    "    \"updateBy\": null,\n" +  
    "    \"updateTime\": \"2023-09-10 19:57:26\"\n" +  
    "}";  
try {  
    JsonNode jsonNode = new ObjectMapper().readTree(json);  
    System.out.println(jsonNode);  
} catch (IOException e) {  
}

上面内容输出

{"aa":"aa","a1":111,"a2":"123","a4":true,"a5":{"sub":"child"}}
[123,"abd",true,{"sub":"child"}]
{"id":"AaEXKZGjdBAQVxtqofPymQmJhuuuupGD","roleName":"临时角色uuuu","roleCode":"test20uuuu33120","description":"这是新建的临时角色123","createBy":"admin","createTime":"2023-09-10 19:57:26","updateBy":null,"updateTime":"2023-09-10 19:57:26"}

jackson版本

<dependency>
      <groupId>com.fasterxml.jackson.coregroupId>
      <artifactId>jackson-databindartifactId>
      <version>2.9.4version>
dependency>

你可能感兴趣的:(Java工具类,知识点小例子,jackson,json字符串转对象,json)