fastjson确实很好用,废话不多说,上代码:
我需要提取的json数据:需要获取json的部分字段赋值给实体对象,并存入数据库。
{
"code": "0",
"data": {
"lives": [
{
"liveType": 1,
"coverUpdate": 90,
"streams": [
{
"coverUrl": "http://livecloudpic.lechange.cn/LCO/6G00A43PAG63E49/0/0/20201207Tc6fbf1b4efa714b.jpg",
"streamId": 0,
"hls": "https://cmgw-vpc.lechange.com:8890/LCO/6G00A43PAG63E49/0/0/20201207T110025/eb0df407b58120b41cb.m3u8?proto=https"
},
{
"coverUrl": "http://livecloudpic.lechange.cn/LCO/6G00A43PAG63E49/0/0/20201207T110025/e20b41c6fbf1b4efa714b.jpg",
"streamId": 1,
"hls": "https://cmgw-ge.com:8890/LCO/6G00A43PAG63E49/0/1/20201207T110025/eb0df407b58120b41c6fbf1b4efa714b.m3u8?proto=https"
},
{
"coverUrl": "http://livecloudpic.lechange.cn/LCO/6G00A43PAG63E49/0/0/20201207T110025/0b41c6fbf1b4efa714b.jpg",
"streamId": 0,
"hls": "http://cmgw-vpc.lechange.com:8888/LCO/6G00A43PAG63E49/0/0/20201207T110025/eb0df407b5bf1b4efa714b.m3u8"
},
{
"coverUrl": "http://livecloudpic.lechange.cn/LCO/6G00A43PAG63E49/0/0/20201207T110025/eb0df407b58120b41c6fbf1b4efa714b.jpg",
"streamId": 1,
"hls": "http://cmgw-vpc.lechange.com:8888/LCO/6G00A43PAG63E49/0/1/20201207T1100bf1b4efa714b.m3u8"
}
],
"liveToken": "f4b5d61806b96ba2d3ef3f9d8ac",
"job": [
{
"period": "always",
"status": true
}
],
"deviceId": "6G00A43E49",
"liveStatus": 1,
"channelId": "0"
}
],
"count": 1
},
"errMsg": "",
"success": true
}
json中数组对象,对象里面又嵌套数组。java后端解析代码;其中result是json字符串。
String results = sbf.toString();
//JSON字符串转换成JSON对象
JSONObject json_o = JSONObject.parseObject(results);
//得到data的json对象
JSONObject jsondata = JSON.parseObject(json_o.getString("data"));
System.out.println(jsondata);
//得到data中的lives对象,并用jsonarr保存
JSONArray jsonarr = jsondata.getJSONArray("lives");
//使用for循环遍历datalist里的json值,如:price,ISBN
for(int i = 0;i<jsonarr.size();i++){
LiveCameraEntity liveCameraEntity=new LiveCameraEntity();
JSONObject jsonb = jsonarr.getJSONObject(i);
liveCameraEntity.setChannelId(jsonb.getString("channelId"));
liveCameraEntity.setDeviceId(jsonb.getString("deviceId"));
//streams数组的处理
JSONArray jsonArray6=jsonb.getJSONArray("streams");
JSONObject jsonarr1 = jsonArray6.getJSONObject(1);
System.out.println("3333333333333333333333333"+jsonarr1);
liveCameraEntity.setCoverUrl(jsonarr1.getString("coverUrl"));
liveCameraEntity.setStreamId(jsonarr1.getInteger("streamId"));
liveCameraEntity.setHls(jsonarr1.getString("hls"));
//job数组的处理
JSONObject jsonarr2=jsonb.getJSONArray("job").getJSONObject(0);
liveCameraEntity.setPeriod(jsonarr2.getString("period"));
liveCameraEntity.setStatus(jsonarr2.getBoolean("status"));
baseMapper.insert(liveCameraEntity);
System.out.println("11111111111111111111111"+liveCameraEntity+"6666666666666666666666");
其中result是json字符串。
总结:不要怕,不要怂,耐着性子,干着干着就出来了。
我搜了很多博客,感觉最好的两篇:https://www.cnblogs.com/ioioi/p/9437096.html