欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

json如何解析混合数组对象到实体类的list集合里去

程序员文章站 2022-03-10 20:48:02
一、前言这次项目中遇到了一个这样的需求,把下面数据解析到我下面的对象里去。json 文件[ { "categories": [ "美食,小吃快餐"...

一、前言

这次项目中遇到了一个这样的需求,把下面数据解析到我下面的对象里去。

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);
  }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。