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",
            "city": "北京市",
            "city_code": "110100",
            "district": "豐臺區",
            "district_code": "110106",
            "floor": "6",
            "latitude": "39.86608",
            "longitude": "116.30516",
            "province": "北京市",
            "province_code": "110000"
        },
        "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();
        } 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”:”[\”美食,面包甜點\”]”,”city”:”北京市”,”cityCode”:”110100″,”district”:”豐臺區”,”districtCode”:”110106″,”floor”:”6″,”latitude”:39.86608,”longitude”:116.30516,”name”:”好客來”,”phone”:”010-65280221″,”poiId”:”3g97sg8sd67″,”province”:”北京市”,”provinceCode”:”110000″}]

我們用工具轉換一下看的更清晰一點:

[
    {
        "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": "["美食,面包甜點"]",
        "city": "北京市",
        "cityCode": "110100",
        "district": "豐臺區",
        "districtCode": "110106",
        "floor": "6",
        "latitude": 39.86608,
        "longitude": 116.30516,
        "name": "好客來",
        "phone": "010-65280221",
        "poiId": "3g97sg8sd67",
        "province": "北京市",
        "provinceCode": "110000"
    }
]

json數組和List集合轉換總結

//方法一,將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':18},{'name':'lisi','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},{'name':'lisi','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);
  }
}

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: