解析JSON
JSR 353 API
常用的第三方库
Jackson
gson
fastjson
Jackson:
提供了读写JSON的API
JSON和JavaBean可以互相转换
可食用Annotation定制序列化和反序列化
Jackson初步使用
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-jsr310</artifactId> <version>2.9.0</version> </dependency>
package com.feiyangedu.sample.pop3; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; public class ParseJsonTest { public static void main(String[] args) { String data = "{\"type\":2,\"range\":1,\"start\":1368417600,\"end\":1368547140," + "\"cityName\":\"天津\",\"companyIds\":[\"12000001\"],\"companyNames\":[\"天津\"]," + "\"12000001\":{\"data\":[47947,48328,48573,48520]," + "\"timestamps\":[1368417600,1368417900,1368418200,1368418500]}}"; String data2 = parseJson(data); System.out.println(data2); } public static String parseJson(String data){ StringBuffer buffer = new StringBuffer(); try{ ObjectMapper mapper = new ObjectMapper(); JsonNode rootNode = mapper.readTree(data); int type = rootNode.path("type").asInt(); int range = rootNode.path("range").asInt(); long start = rootNode.path("start").asLong(); long end = rootNode.path("end").asLong(); String cityName = rootNode.path("cityName").asText(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm"); sdf.setTimeZone(TimeZone.getTimeZone("GMT+8")); String str = "类型(type):"+type+"\r\n"+"范围(range):"+range+"\r\n"+ "开始时间(start):"+sdf.format(new Date(start*1000))+"\r\n"+"结束时间(end):"+sdf.format(new Date(end*1000))+"\r\n"+ sdf.format(new Date(end*1000))+"\r\n"+"城市名称(cityName):"+cityName; buffer.append(str); JsonNode companyIds = rootNode.path("companyIds"); JsonNode companyNames = rootNode.path("companyNames"); for(int i=0;i<companyIds.size();i++){ String companyId = companyIds.get(i).asText(); String companyName = companyNames.get(i).asText(); JsonNode infoNode = rootNode.path(companyId); JsonNode dataNode = infoNode.path("data"); JsonNode timestampsNode = infoNode.path("timestamps"); buffer.append("\r\n{\r\n 公司ID(companyId):"+companyId+"\r\n 公司名称(companyName):"+companyName+"\r\n"+"data:"); for(int j=0;j<dataNode.size();j++){ long dataValue = dataNode.get(j).asLong(); buffer.append(dataValue+","); } buffer.append("\r\n timestamp:"); for(int k=0;k<timestampsNode.size();k++){ long timeValue = timestampsNode.get(k).asLong(); buffer.append(sdf.format(new Date(timeValue*1000))+","); } buffer.append("\r\n}\r\n"); } }catch (JsonProcessingException e){ e.printStackTrace();; }catch (IOException e){ e.printStackTrace(); } return buffer.toString(); } }
总结:
Jackson提供了读写JSON和JavaBean的互相转换
可使用Annotation定制序列化和反序列化