json如何解析混合陣列物件到實體類的list集合裡去
一、前言
這次專案中遇到了一個這樣的需求,把下面資料解析到我下面的物件裡去。
json 檔案
[ { "categories": [ "美食,小吃快餐" ],"coordinate": { "address": "王府井大街138號新東安廣場3層328","area": "東安市場","area_id": "jk238eewf0k","city": "北京市","city_code": "110100","district": "東城區","district_code": "110101","floor": "3","latitude": "39.91456","longitude": "116.41155","province": "北京市","province_code": "110000" },"name": "探魚","phone": "010-65280328","poi_id": "d7s8f6s6212" },{ "categories": [ "美食,麵包甜點" ],"coordinate": { "address": "豐臺北路18號院恆泰廣場F6樓","area": "恆泰廣場","area_id": "ji8sgg3b32o"http://www.cppcns.com,"district": "豐臺區","district_code": "110106","floor": "6","latitude": "39.86608","longitude": "116.30516","name": "好客來","phone": "010-65280221","poi_id": "3g97sg8sd67" } ]
實體物件:
public class LocatorData { // 分類 private String categories; // 商圈 private String area; // 商圈id private String areaId; // 省份 private String province; // 省份code private String provinceCode; // 城市 private String city; // 城市code private String cityCode; // 區縣 private String district; // 區縣code private String districtCode; // 樓層 private String floor; // 經度 private Double latitude; // 維度 private Double longitude; // 店鋪名稱 private String name; // 店鋪地址 private String address; // 店鋪電話 private String phone; // 店鋪id private String poiId; }
不知道小夥伴有沒有發現,我這裡只是一個物件,沒有一對多的關係哈,要的就是這樣的效果。
但 json 檔案裡有個 coordinate 物件,而我實體物件不需要這個欄位。那也沒關係,一步步解析就完事了。
@RestController public class ParseController { private static final Logger LOGGER = LoggerFactory.getLogger(EasyExcelController.class); @PostMapping(value = "/arrayObjectNestingParse",produces = "application/json;charset=UTF-8") public ReturnT<String> arrayObjectNestingParse(@RequestParam(value = "jsonFile") MultipartFile jsonFile) { if (jsonFile == null) { return new ReturnT<>(ReturnT.BAD_REQUEST,"Params can not be null"); } InputStream is = null; BufferedReader br = null; StringBuffer sb = new StringBuffer(); String str = null; try { is = jsonFile.getInputStream(); br = new BufferedReader(new InputStreamReader(is)); while ((str = br.readLine()) != null) { sb.append(str); } } catch (IOException e) { e.printStackTrace(); www.cppcns.com} finally { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } List<LocatorData> locatorDataList = new ArrayList<>(); JSONArray jsonArray = JSONArray.parseArray(sb.toString()); for (int i = 0; i < jsonArray.size(); i++) { LocatorData locatorData = new LocatorData(); JSONObject jsonObject = jsonArray.getJSONObject(i); String categories = jsonObject.getString("categories"); String coordinate = jsonObject.getString("coordinate"); JSONObject coordinateObj = JSONObject.parseObject(coordinate); String address = coordinateObj.getString("address"); String area = coordinateObj.getString("area"); String areaId = 程式設計客棧coordinateObj.getString("area_id"); String city = coordinateObj.getString("city"); String cityCode = coordinateObj.getString("city_code"); String district = coordinateObj.getString("district"); String districtCode = coordinateObj.getString("district_code"); String floor = coordinateObj.getString("floor"); String latitude = coordinateObj.getString("latitude"); String longitude = coordinateObj.getString("longitude"); String province = coordinateObj.getString("province"); String provinceCode = coordinateObj.getString("province_code"); String name = jsonObject.getString("name"); String phone = jsonObject.getString("phone"); String poiId = jsonObject.getString("poi_id"); locatorData.setCategories(categories); locatorData.setAddress(address); locatorData.setArea(area); locatorData.setAreaId(areaId); locatorData.setProvince(province); locatorData.setProvinceCode(provinceCode); locatorData.setCity(city); locatorData.setCityCode(cityCode); locatorData.setDistrict(district); locatorData.setDistrictCode(districtCode); locatorData.setFloor(floor); locatorData.setLatitude(Double.parseDouble(latitude)); locatorData.setLongitude(Double.parseDouble(longitude)); locatorData.setName(name); locatorData.setPhone(phone); locatorData.setPoiId(poiId); locatorDataList.add(locatorData); } LOGGER.info("locatorDataList: " + JSON.toJSONString(locatorDataList)); return new ReturnT<>(ReturnT.SUCCESS,JSON.toJSONString(locatorDataList)); } }
日誌列印:
2020-01-07 00:39:30.284 [http-nio-8080-exec-3] INFO c.r.springbootdemo.controller.EasyExcelController-locatorDataList: [{"address":"王府井大街138號新東安廣場3層328","area":"東安市場","areaId":"jk238eewf0k","categories":"[\"美食,小吃快餐\"]","city":"北京市","cityCode":"110100","district":"東城區","districtCode":"110101","floor":"3","latitude":39.91456,"longitude":116.41155,"name":"探魚","phone":"010-65280328","poiId":"d7s8f6s6212","province":"北京市","provinceCode":"110000"},{"address":"豐臺北路18號院恆泰廣場F6樓","area":"恆泰廣場","areaId":"ji8sgg3b32o","categories":"[\"美食,麵包甜點\"]","district":"豐臺區","districtCode":"110106","floor":"6","latitude":39.86608,"longitude":116.30516,"name":"好客來","phone":"010-65280221","poiId":"3g97sg8sd67","provinceCode":"110000"}]
我們用工具轉換一下看的更清晰一點:
[
{
"address": "王府井大街138號新東安廣場3層328","areaId": "jk238eewf0k","categories": "["美食,小吃快餐"]","cityCode": "110100","districtCode": "110101","latitude": 39.91456,"longitude": 116.41155,"poiId": "d7s8f6s6212","provinceCode": "110000"
},{
"address": "豐臺北路18號院恆泰廣場F6樓","areaId": "ji8sgg3b32o","categories": "["美食,麵包甜點"]","districtCode": "110106","latitude": 39.86608,"longitude": 116.30516,"phone": "0www.cppcns.com10-65280221","poiId": "3g97sg8sd67","provinceCode": "110000"
}
]
json陣列和Lis程式設計客棧t集合轉換總結
//方法一,將json解析後賦給單獨的元素 String jstr="{'json':'jsonvalue','bool':true,'int':1,'double':'20.5'}"; JSONObject json=JSONObject.fromObject(jstr); boolean bool=json.getBoolean("bool"); int i=json.getInt("int"); double d=json.getDouble("double"); String value=json.getString("json"); System.out.println("bool="+String.valueOf(bool)+"\tjson="+value+"\tint="+i+"\tdouble="+d);
//方法二,json物件和bean物件之間相互轉換 //假如你是有一個bean物件 class User{ private String name; private String psw; //封裝getter/setter省略 } //把一個json物件變成user String u="{'name':'sail331x','psw':'123456789'}"; //用user物件接收json中的元素 User user=(User)JSONObject.toBean(JSONObject.fromObject(u),User.class); //把一個user變成json物件: JSONObject juser=JSONObject.fromObject(user); //json字串jstr String jstr=juser.toString();
//方法三,json物件直接轉list集合、list集合轉json物件 //宣告一個Person 實體類: import java.util.Date; public class Person { String id; int age; String name; Date birthday; //get,set方法省略 } //測試json資料轉換 import java.util.Iterator; import java.util.List; import org.junit.Test; import net.sf.json.JSONArray; import net.sf.json.JsonConfig; public class JsonToList { public static void main(String[] args) { String json="[{'name':'zhuangsan','age':18},{'name':'lisi','age':20}]"; JSONArray jsonarray = JSONArray.fromObject(json); System.out.println(jsonarray); List list = (List)JSONArray.toCollection(jsonarray,Person.class); Iterator it = list.iterator(); while(it.hasNext()){ Person p = (Person)it.next(); System.out.println(p.getAge()); } } @Test public void jsonToList1(){ String json="[{'name':'zhuangsan','age':20}]"; JSONArray jsonarray = JSONArray.fromObject(json); System.out.println(jsonarray); List list = (List)JSONArray.toList(jsonarray,Person.class); Iterator it = list.iterator(); while(it.hasNext()){ Person p = (Person)it.next(); System.out.println(p.getAge()); } } @Test public void jsonToList2(){ String json="[{'name':'zhuangsan','age':20},'age':18}]"; JSONArray jsonarray = JSONArray.fromObject(json); System.out.println(jsonarray); System.out.println("------------"); List list = (List)JSONArray.toList(jsonarray,new Person(),new JsonConfig()); Iterator it = list.iterator(); while(it.hasNext()){ Person p = (Person)it.next(); System.out.println(p.getAge()); } } } //將list物件轉為JSON字串陣列: import java.util.LinkedList; import java.util.List; import net.sf.json.JSONArray; public class ListToJson { public static void main(String[] args) { List list = new LinkedList(); for(int i=0;i<3;i++){ Person p = new Person(); p.setAge(i); p.setName("name"+i); list.add(p); } JSONArray jsonarray = JSONArray.fromObject(list); System.out.println(jsonarray); } }
以上為個人經驗,希望能給大家一個參考,也希望大家多多支援我們。