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

JSON常用对象转换

程序员文章站 2022-03-14 15:55:56
...

记录一下平常常用的处理JSON串的方法,下面是待处理的JSON串:

{"code":200,"msg":"success","data":[{"city_id":"311","city_name":"阿拉善","admin_code":"152900","initial":"A","prov_id":"33","prov_name":"内蒙古"},{"city_id":"379","city_name":"阿坝","admin_code":"513200","initial":"A","prov_id":"22","prov_name":"四川"},{"city_id":"171","city_name":"阿里","admin_code":"542500","initial":"A","prov_id":"30","prov_name":"*"},{"city_id":"225","city_name":"阿克苏","admin_code":"652900","initial":"A","prov_id":"32","prov_name":"*"},{"city_id":"390","city_name":"阿勒泰","admin_code":"654300","initial":"A","prov_id":"32","prov_name":"*"},{"city_id":"66","city_name":"鞍山","admin_code":"210300","initial":"A","prov_id":"8","prov_name":"辽宁"}]}
String msg = "{\"code\":200,\"msg\":\"success\",\"data\":[{\"city_id\":\"311\",\"city_name\":\"阿拉善\",\"admin_code\":\"152900\",\"initial\":\"A\",\"prov_id\":\"33\",\"prov_name\":\"内蒙古\"},{\"city_id\":\"379\",\"city_name\":\"阿坝\",\"admin_code\":\"513200\",\"initial\":\"A\",\"prov_id\":\"22\",\"prov_name\":\"四川\"},{\"city_id\":\"171\",\"city_name\":\"阿里\",\"admin_code\":\"542500\",\"initial\":\"A\",\"prov_id\":\"30\",\"prov_name\":\"*\"},{\"city_id\":\"225\",\"city_name\":\"阿克苏\",\"admin_code\":\"652900\",\"initial\":\"A\",\"prov_id\":\"32\",\"prov_name\":\"*\"},{\"city_id\":\"390\",\"city_name\":\"阿勒泰\",\"admin_code\":\"654300\",\"initial\":\"A\",\"prov_id\":\"32\",\"prov_name\":\"*\"},{\"city_id\":\"66\",\"city_name\":\"鞍山\",\"admin_code\":\"210300\",\"initial\":\"A\",\"prov_id\":\"8\",\"prov_name\":\"辽宁\"}]}";
        //字符串转JSONObject
        JSONObject json = JSON.parseObject(msg);
        //获取JSON串里的属性
        String data = json.get("data").toString();
        //json数组转换为List对象
        List<CityDTO> cityList=JSONObject.parseArray(data,CityDTO.class);

又或者是实体类转化为JSON字符串:

//实体类转换JSON字符串
JSON.toJSONString(model)

引用的Maven依赖

        <!-- fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>

以后有新的再添加,这3个应该够用了。

相关标签: JSON转换