首页  

Jackson JSON的三种处理方式     所属分类 jackson 浏览量 96
数据绑定
树模型
流式API

测试数据
{"id":1,"name":"Department1","users":[{"id":1,"name":"cat"},{"id":2,"name":"tiger"}]}


数据绑定 ObjectMapper mapper = new ObjectMapper(); Department dept = mapper.readValue(json, Department.class); System.out.println(dept);
树模型 JsonNode rootNode = mapper.readTree(json); System.out.println(rootNode); JsonNode idNode = rootNode.get("id"); JsonNode nameNode = rootNode.get("name"); JsonNode nullNode = rootNode.get("xxx"); JsonNode nullNodeByPath = rootNode.path("xxx"); System.out.println("idNode="+idNode); System.out.println("nameNode="+nameNode); System.out.println("nullNode="+nullNode); System.out.println("nullNodeByPath="+nullNodeByPath); System.out.println("idNode isArray "+idNode.isArray()); System.out.println("idNode size "+idNode.size()); System.out.println("idNode "+idNode.asInt() +" "+idNode.asText()); JsonNode usersNode = rootNode.get("users"); System.out.println("usersNode="+usersNode); if(usersNode.isArray()) { int size = usersNode.size(); for(int i=0;i < size;i++) { JsonNode userNode = usersNode.get(0); System.out.println("userNodes["+i+"]="+userNode); } }
流式API JsonFactory factory = new JsonFactory(); JsonParser parser = factory.createParser(json); while (!parser.isClosed()){ JsonToken token = parser.currentToken(); System.out.println(token); parser.nextToken(); } START_OBJECT FIELD_NAME VALUE_NUMBER_INT FIELD_NAME VALUE_STRING FIELD_NAME START_ARRAY START_OBJECT FIELD_NAME VALUE_NUMBER_INT FIELD_NAME VALUE_STRING END_OBJECT START_OBJECT FIELD_NAME VALUE_NUMBER_INT FIELD_NAME VALUE_STRING END_OBJECT END_ARRAY END_OBJECT
完整代码 https://gitee.com/dyyx/demos/blob/master/jackson/src/main/java/dyyx/jackson/TestAll.java

上一篇     下一篇
SpringMVC consumes 和 produces 用法

SpringMVC 数据验证

AspectJ简介及实例

Springboot监控端点Actuator实例

SpringIoC容器要点

JavaConfig与常见的Annotation