JSON解析案例1
将String转为JSONObject
JSONObject res = JSONObject.parseObject(result);
获取documents
JSONArray array = res.getJSONObject("result").getJSONArray("documents");
遍历JSONArray
for (int i = 0; i < array.size(); i++) {
JSONObject object = array.getJSONObject(i);
String id = object.getString("id");
object.put("id", id.substring(0,id.length()-3));
}
JSONArray处理好后再转为List
List<SearchResultDto> listResult = JSONObject.parseArray(array.toJSONString(), SearchResultDto.class);
JSON解析案例2
Java解析:
输出结果:
对象转jsonStr
import com.alibaba.fastjson.JSON;
String message = JSON.toJSONString(person);
jsonStr转对象:
import com.alibaba.fastjson.JSONObject;
Person person = JSONObject.parseObject(message, Person.class);
jsonListStr转为List
List<Device> devices = JSONArray.parseArray(rsp, Device.class);
或者:
JSONObject resJson=JSONObject.parseObject(jsonStr);
List<SsqdPageVo> ssqdPageVos = resJson.getJSONArray("data").toJavaList(SsqdPageVo.class);
str = “[“2021-08-05”,“2021-08-07”]”
JSONArray value = JSONArray.parseArray(str);
jsonStr转JSONObject
String jsonStr= "{"name": "张三", "age": 24, "city": "宜昌"}";
JSONObject jsonObj = JSONObject.parseObject(jsonStr);
String name = jsonObj .getString("name");
System.out.println(name);
JSONObject转实体类
JSONObject jsonObj = JSONObject.parseObject(jsonStr);
JSONObject userJsonObj = (JSONObject)jsonObj.get("params");
Users users = JSON.toJavaObject(userJsonObj, Users.class);
map转jsonStr
String jsonStr = JSON.toJSONString(map)
jsonStr转map
String jsonStr = '{"Ss":[{"areaCode":"340100000000","areaCodeLng":"117.228949","areaName":"合肥市","gaPlaceNum":"6","areaCodeLat":"31.821719","cftpPlaceNum":"0"}],"Ah":[{"areaCode":"340000000000","areaCodeLng":"117.300552","areaName":"安徽省","gaPlaceNum":"15","areaCodeLat":"31.833219","cftpPlaceNum":"0"}],"Ds":[{"areaCode":"340103000000","areaCodeLng":"117.252877","areaName":"庐阳区","gaPlaceNum":"2","areaCodeLat":"31.898528","cftpPlaceNum":"0"},{"areaCode":"340122000000","areaCodeLng":"117.463222","areaName":"肥东县","gaPlaceNum":"1","areaCodeLat":"31.883992","cftpPlaceNum":"0"}]}
';
JSONObject jsonObject = JSONObject.parseObject(jsonStr);
Map map = jsonObject.toJavaObject(Map.class);
map转对象
T和entityClass应该是同一个类型
T o= (T) JSON.parseObject(JSON.toJSONString(map),entityClass);