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个应该够用了。
上一篇: 什么是有效教学
下一篇: 16进制与字符串相互转换(C语言)
推荐阅读
-
将json对象转换为字符串的方法_javascript技巧
-
C#中DataTable 转换为 Json的方法汇总(三种方法)
-
php怎么样才可以转换成这样的Json格式
-
javascript-JS 的时间格式与JSON时间格式如何互相转换?
-
怎样使用JS实现json对象数组按对象属性排序
-
PHP常用功能块_异常与时间戳 — php(33),php时间戳转换
-
js protobuf 实例对象在JSON转换时遇到的问题
-
php 多条json 转换为数组解决思路
-
php简单对象与数组的转换函数代码(php多层数组和对象的转换)_php技巧
-
PHP object(SimpleXMLElement) 对象转换为数组