fastjson取值,取出想要的欄位新增給實體物件
阿新 • • 發佈:2021-01-07
技術標籤:springbootjavajson字串
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