之前解析 json 格式一直使用jsonObject,jsonArray,虽然使用起来还算可以,但后来发现可以使用实体类映射,貌似也还可以。而且代码复用性比较好。
使用工具
idea,com.alibaba.fastjson.JSON
json数据 {"website":"chinamobilesh","create_time":157360,"basic_version":{ "user_gender": "男", "user_searched_history_by_orgs": [ { "org_self": true, "searched_date": "2017-11-07", "searched_org": "其他" }, { "org_self": false, "searched_date": "2017-07-08", "searched_org": "线上消费分期" }, ] }}
String 格式
String data = "{"website":"chinamobilesh", "create_time":157360, "basic_version":{"user_gender": "男","user_searched_history_by_orgs": [{"org_self": true,"searched_date": "2017-11-07","searched_org": "其他"},{"org_self": false,"searched_date": "2017-07-08","searched_org": "线上消费分期"}]}}"; pojo实体类
可以参考 json在线解析
package com.pojo;import java.util.List;public class Root { private String website; private int createTime; private BasicVersion basicVersion; //省略getter/setter... public static class UserSearchedHistoryByOrgs { private boolean orgSelf; private String searchedDate; private String searchedOrg; //省略getter/setter... } public static class BasicVersion { private String userGender; private List<UserSearchedHistoryByOrgs> userSearchedHistoryByOrgs; //省略getter/setter...} 解析 Root root = JSON.parseObject(data,Root.class); BasicVersion basicVersion = root.getBasicVersion(); String userGender= basicVersion.getUserGender(); System.out.println(userGender);
结果:男