fastjson 的使用
官网
https://github.com/alibaba/fastjson/wiki
这里可以查看,自己的项目依赖该项目。
jsonpath
https://github.com/alibaba/fastjson/wiki/JSONPath
可以获取任意路径下的任何格式的数据。
实体类和jsonString,互转
entity 是一个实体类的对象
import com.alibaba.fastjson.JSON;
String jsonString = JSON.toJSONString(entity);
System.out.println(jsonString);
String jsonString = ...;
entity = JSON.parseObject(jsonString, Entity.class);
jsonarray转listArray
line = {"result":[{"count":0,"name":"自身风险","list":[],"type":1}], "arr2":[["e":0], ["e":1]]}
JSONObject jsonObject = JSON.parseObject(line);
JSONArray nameList = (JSONArray) JSONPath.eval(jsonObject, "$.result");
jsonString 转多维维数组
line = {"result":[[{"count":0,"name":"自身风险","list":[],"type":1}]}
JSONObject jsonObject = JSON.parseObject(line);
//取出第一层
JSONArray nameList = (JSONArray) JSONPath.eval(jsonObject, "$.result");
// 写个for循环,依次取出nameList中的jsonarray
JSONObject nameObject = (JSONObject) JSONPath.eval(jsonObject, "$.arr2");
jsonString 取出任意的元素
不通过实体类, 3层for循环
JSONObject jsonObject = JSON.parseObject(line);
JSONArray nameList = (JSONArray) JSONPath.eval(jsonObject, "$.result");
for (Iterator iterator = nameList.iterator(); iterator.hasNext(); ) {
JSONObject tagObject = (JSONObject) iterator.next();
JSONArray tagList = tagObject.getJSONArray("list");
// if (tagList != null && !tagList.isEmpty()){
for (Iterator iteratort = tagList.iterator(); iteratort.hasNext(); ) {
JSONObject riskbject = (JSONObject) iteratort.next();
JSONArray riskList = riskbject.getJSONArray("list");
for (Iterator iteratort1 = riskList.iterator(); iteratort1.hasNext(); ) {
JSONObject childbject = (JSONObject) iteratort1.next();
Object title = childbject.get("title");
Object id = childbject.get("id");
}
}
}