<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.83</version>
</dependency>
package com.coco;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class fast {
public static void main(String[] args) {
User user = new User("小雨",15);
List<User> list = new ArrayList<User>();
list.add(user);
list.add(new User("小雪",18));
Users users = new Users(1,list);
//object转string
String s = JSON.toJSONString(user);
System.out.println(s);
//list转string
String s1 = JSON.toJSONString(list);
System.out.println(s1);
//复杂object转string
String s2 = JSON.toJSONString(users);
System.out.println(s2);
//string转json对象
JSONObject jsonObject = JSON.parseObject(s);
System.out.println(jsonObject);
//string转java对象
User user1 = JSON.parseObject(s, User.class);
System.out.println(user1);
//string转jsonArray
JSONArray objects = JSON.parseArray(s1);
System.out.println(objects);
//string转list对象
List<User> users1 = JSON.parseArray(s1, User.class);
System.out.println(users1.toString());
//string转复杂java对象
Users users2 = JSON.parseObject(s2, Users.class);
System.out.println(users2.toString());
//获取json对象值
JSONObject jsonObject1 = JSON.parseObject(s2);
System.out.println(jsonObject1);
//get返回object
Object list1 = jsonObject1.get("list");
System.out.println(list1.getClass());
//getString返回string
String list2 = jsonObject1.getString("list");
System.out.println(list2.getClass());
//map转json
Map<String, User> map = new HashMap<>();
map.put("1", list.get(0));
map.put("2", list.get(1));
String s3 = JSON.toJSONString(map);
System.out.println(s3);
//json转map
Map<String, User> stringObjectMap = JSON.parseObject(s3, new TypeReference<Map<String, User>>() {});
System.out.println(stringObjectMap.getClass());
//jsonObject相当于Map<String,Object>
JSONObject jsonObject2 = JSON.parseObject(s3);
jsonObject2.put("3","{'age':14,'name':'小冰'}");
System.out.println(jsonObject2);
}
}