利用fastjson工具实现JSON、对象、数组、map互转
一、工具介绍
关于Object转换Json,常用的框架并不多,主要是这几个:
- Jackson: 这个框架基本成为了Spring的标配。
- FastJson : 这个是国内的,出自阿里的开源json框架,效率会比较高。
- Gson : 没怎么用过。
这里阐述使用FastJson工具
由于json格式经常容易写错,所以推荐个json校验工具:http://www.bejson.com/
FastJson入门教程参考W3Cschool: https://www.w3cschool.cn/fastjson/fastjson-ex1.html
fastjson.jar包原始下载地址:https://github.com/alibaba/fastjson
二、springboot进行集成FastJson。
导包
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.61</version>
</dependency>
三、使用
1、对象<-->JSON
//下面的student为对象
// TODO 用户对象转JSON串
String jsonString = JSON.toJSONString(student);
System.out.println("jsonString:" + jsonString);
// TODO JSON串转用户组对象
UserGroup student2= JSON.parseObject(jsonString, Student.class);
System.out.println("student2:" + student2);
2、数组->json字符串->list
// 构建用户对象数组
User[] users = new User[]{user1,user2};
// 用户对象数组转JSON串
String jsonString2 = JSON.toJSONString(users);
System.out.println("jsonString2:" + jsonString2);
// JSON串转用户对象列表
List<User> users2 = JSON.parseArray(jsonString2, User.class);
System.out.println("users2:" + users2);
3、List -> JSON array JSON array -> List
//List -> JSON array
List<Bar> barList = new ArrayList<Bar>();
barList.add(new Bar());
barList.add(new Bar());
barList.add(new Bar());
String json= JSON.toJSONString(barList, true);
System.out.println(json);
//JSON array -> List
List<Bar> barList1 = JSON.parseArray(json,Bar.class);
for (Bar bar : barList1) {
System.out.println(bar.toString());
}
4、Map -> JSON JSON -> Map
//Map -> JSON
Map<String,Bar> map = new HashMap<String, Bar>();
map.put("a",new Bar());
map.put("b",new Bar());
map.put("c",new Bar());
String json = JSON.toJSONString(map,true);
System.out.println(json);
//JSON -> Map
Map<String,Bar> map1 = (Map<String,Bar>)JSON.parse(json);