public class Test {
public static void main(String[] args) {
// 实现java对象与Json字符串之间的转化
// 1. Person对象与json之间的转换
//1.1 将Person对象转成json
Person p = new Person(10, "张三");
Object obj = JSONArray.toJSON(p);
String json = obj.toString();
System.out.println("将Person对象转成json:" + json);
//1.2 将json字符串转成Person对象
Person person = JSONArray.parseObject(json, Person.class);
System.out.println("person.getName():" + person.getName());
// 2. 将List<Person>与json之间的转换
//2.1 将List<Person>转成json
List<Person> personList = new ArrayList<>();
personList.add(new Person(10, "张三"));
personList.add(new Person(10, "李四"));
personList.add(new Person(10, "王五"));
Object obj2 = JSONArray.toJSON(personList);
String json2 = obj2.toString();
System.out.println("将List<Person>转成json:" + json2);
// 2.2. 将json字符串转成List<Person>对象
List<Person> list = JSONArray.parseArray(json2, Person.class);
System.out.println("list.size():" + list.size());
// 3. 将Map对象与json之间的转换
// 3.1 将Map转成json
Map<String, Person> map = new HashMap<>();
map.put("1", new Person(10, "张三"));
map.put("2", new Person(10, "李四"));
map.put("3", new Person(10, "王五"));
Object obj3 = JSONArray.toJSON(map);
String json3 = obj3.toString();
System.out.println("将Map<String,Person>转成json:" + json3);
// 3.2. 将json转成Map对象
Map<String, Object> map2 = JSONArray.parseObject(json3);
Person person2 = JSONArray.parseObject(map2.get("1").toString(), Person.class);
System.out.println("person2.getName():" + person2.getName());
}
}