文章转自:https://blog.csdn.net/weixin_40516924/article/details/115704023?spm=1001.2014.3001.5506


SerializeWriter:相当于StringBuffer
JSONArray:相当于List
JSONObject:相当于Map<String, Object>
JSON反序列化没有真正数组,本质类型都是List

以 Student 对象为例 Student类要实现Serializable接口

import java.io.Serializable;

public class Student implements Serializable {
   private static final long serialVersionUID = -6957361951748382519L;
   private String id;

  // 省略
} 

相关依赖:

<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>2.0.8</version>
</dependency>

1. List —> Json字符串

List<Student> students = new ArrayList();
String str = JSON.toJSONString(students); // List转json

2. Json字符串 —> List

String json = ""; //获取的Json数据

// 方法一
List<Student> students = JSON.parseObject(json,new TypeReference<List<Student>>(){}); // Json 转List

// 方法二
List<Student> students = JSON.parseArray(json,Student.class); 

3. JAVA对象 —> JSON字符串

Student s = new Student();
String jsonString = JSON.toJSONString(s);

4. JAVA对象 —> JSON对象

Student s = new Student();

// 方法一
JSONObject jsonObj = (JSONObject) JSON.toJSON(s);

// 方法二
JSON json = (JSON) JSON.toJSON(data)

5. JSON字符串 —> Java对象

Student s = JSON.parseObject(e.getMessage(), Student.class);

6. JSON字符串 —> Json对象

JSONObject jsonObject = JSON.parseObject(jsonString);