首先是使用这个包com.alibaba.fastjson.JSON 需要引入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.58</version>
</dependency>
定义一个bean1类
@Data
public class Bean1 {
private Integer age;
private String name;
private Integer score;
}
定义一个bean2类
@Data
public class Bean2 {
private List<Bean1> content;
}
JSON.parseArray定义一个测试类
import com.alibaba.fastjson.JSON;
import java.util.ArrayList;
import java.util.List;
public class MyTest {
public static void main(String[] args) {
Bean1 bean1_1 = new Bean1();
bean1_1.setAge(1);
bean1_1.setName("jjw");
bean1_1.setScore(60);
Bean1 bean1_2 = new Bean1();
bean1_2.setAge(18);
bean1_2.setName("whz");
bean1_2.setScore(90);
ArrayList arrayList = new ArrayList();
arrayList.add(bean1_1);
arrayList.add(bean1_2);
Bean2 bean2 = new Bean2();
bean2.setContent(arrayList);
System.out.println(bean2);
// 将ArrayList类型转换成json格式的字符串类型
String a = JSON.toJSONString(bean2.getContent());
System.out.println(a);
System.out.println(a instanceof String);
// 将字符串类型转换成json类型,第一个参数表示要转换的字符串,第二个表示数组中的类
List<Bean1> bean1s = JSON.parseArray(a, Bean1.class);
Bean1 bean1 = bean1s.get(0);
System.out.println(bean1.getName());
}
}
输出结果:
Bean2(content=[Bean1(age=1, name=jjw, score=60), Bean1(age=18, name=whz, score=90)])
[{"age":1,"name":"jjw","score":60},{"age":18,"name":"whz","score":90}]
true
jjw
JSON.parseObject
Bean1 bean1 = new Bean1();
bean1.setScore(90);
bean1.setName("jjw");
bean1.setAge(18);
String s = JSON.toJSONString(bean1);
Bean1 bean11 = JSON.parseObject(s, Bean1.class);
System.out.println(bean11.getName());
System.out.println(bean11.getAge());
System.out.println(bean11.getScore());
输出结果:
jjw
18
90