什么是JSON数据?
{
"id":1,
"age":20,
"name":"张三"
}
JSON使用的是阿里提供的fastjson,需要提前引入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.71</version>
</dependency>
1.JSON.toJSONString:将对象转换为JSON字符串
2.JSON.parseObject:将JSON字符串转换为实体类对象
3.JSON.parseArray:将JSON字符数组转换为list
测试:
Student.java
public class Student{
private Integer id;
private String name;
private Integer age;
}
TestJSON.java
Student student = new Student(1, "张三", 20);
System.out.println("1.原始对象student:"+student);
//1.JSON.toJSONString:将对象转换为JSON字符串
String studentStr = JSON.toJSONString(student);
System.out.println("2.转换为JSON字符串:"+studentStr);
//2.JSON.parseObject:将JSON字符串转换为JSON对象,需要指定转换的实体类型
//注意:提示尽量保持实体类型的属性名和类型与JSON字符串中的一致
Student studentObj = JSON.parseObject(studentStr, Student.class);
System.out.println("3.转换为JSON对象:"+studentObj);
ArrayList<String> list = new ArrayList<>();
list.add(JSON.toJSONString(new Student(2, "李四", 21)));
list.add(JSON.toJSONString(new Student(3, "王五", 22)));
list.add(JSON.toJSONString(new Student(4, "赵六", 23)));
System.out.println("4.原始list:"+list);
//此处由于测试没有JSON字符串,需要转一下,注意,数组里面放的是JSON字符串!!
//1.转换为JSON字符串
String listStr = list.toString();
System.out.println("5.list转换为String:"+listStr);
//2.将JSON字符串转换为对象数组
List<Student> listObj = JSON.parseArray(listStr, Student.class);
System.out.println("6.String转换为list:"+listObj);
结果展示:
1.原始对象student:Student(id=1, name=张三, age=20)
2.转换为JSON字符串:{"age":20,"id":1,"name":"张三"}
3.转换为JSON对象:Student(id=1, name=张三, age=20)
4.原始list:[{"age":21,"id":2,"name":"李四"}, {"age":22,"id":3,"name":"王五"}, {"age":23,"id":4,"name":"赵六"}]
5.list转换为String:[{"age":21,"id":2,"name":"李四"}, {"age":22,"id":3,"name":"王五"}, {"age":23,"id":4,"name":"赵六"}]
6.String转换为list:[Student(id=2, name=李四, age=21), Student(id=3, name=王五, age=22), Student(id=4, name=赵六, age=23)]