json怎么解析混合数组对象到实体类的list集合中
更新:HHH   时间:2023-1-7


小编给大家分享一下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);
  }
}

看完了这篇文章,相信你对“json怎么解析混合数组对象到实体类的list集合中”有了一定的了解,如果想了解更多相关知识,欢迎关注天达云行业资讯频道,感谢各位的阅读!

返回开发技术教程...