JSON常用对象转换

记录一下平常常用的处理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个应该够用了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值