版权声明:★Study hard and make progress every day.☺★ https://blog.csdn.net/qq_38225558/article/details/86500791
项目导入依赖:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.30</version>
</dependency>
测试:
public class FastJsonTest {
//对象转换为json字符串,json字符串转换java对象
//JSONObject/JSONArray.toJSONString JSONObject.parseObject JSONArray.parseArray
@Test
public void test() throws Exception {
Person zs = new Person(1L, "zs");
//单个对象 --> json对象
String jsonObj = JSONObject.toJSONString(zs);
System.out.println(jsonObj);
//集合 --> json数组
String jsonArray = JSONArray.toJSONString(Arrays.asList(zs, zs,new Person(2L, "ls")));
System.out.println(jsonArray);
//json对象 --> 单个对象
Person person = JSONObject.parseObject(jsonObj, Person.class);
System.out.println(person);
//json数组 --> 集合
List<Person> persons = JSONArray.parseArray(jsonArray, Person.class);
System.out.println(persons);
}
}
public class Person {
private Long id;
private String name;
public Person() { }
//getter/setter方法+toString方法...
}
运行结果: