一、导入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
二、编写程序
import com.alibaba.fastjson.JSON;
import java.util.ArrayList;
import java.util.List;
/**
* @Author shall潇
* @Date 2021/5/27
* @Description
*/
public class FastDemo {
public static void main(String[] args) {
String s = "{'name':'Tom','age':23}";
Student s1 = new Student("Jack",34);
Student s2 = new Student("Hans",44);
List<Student> list = new ArrayList<>();
list.add(s1);
list.add(s2);
// 1.对象转成JSON字符串
String s3 = JSON.toJSONString(list);
System.out.println(s3);
// 2.JSON字符串转成对象
Student student1 = JSON.parseObject(s, Student.class);
System.out.println(student1);
}
}
class Student{
String name;
int age;
public Student() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
运行结果: