JSON 对对象和map进行转换 toJSONString parseObject
JSONArray 对数组和集合进行转换 toJSONString parseArray
数组类型
public static void main(String[] args) {
String[] names = {"张三","李四","王五"};
System.out.println(Arrays.toString(names));//[张三, 李四, 王五]
//把java的数组类型转换成json格式字符串
String jsonString = JSONArray.toJSONString(names);
System.out.println(jsonString);//["张三","李四","王五"]
//把json格式字符串转换成java集合类型
List<String> list = JSONArray.parseArray(jsonString, String.class);
System.out.println(list);//[张三, 李四, 王五]
}
普通实例对象
public static void main(String[] args) {
Student s = new Student(1,"张三",20);
//把java普通实例对象转换成json格式字符串
String jsonString = JSON.toJSONString(s);
System.out.println(jsonString);//{"age":20,"id":1,"name":"张三"}
//把json格式字符串转换成java普通实例对象
Student student = JSON.parseObject(jsonString, Student.class);
System.out.println(student);
}
集合
public static void main(String[] args) {
List<Student> list = new ArrayList<>();
list.add(new Student(1,"张三",20));
list.add(new Student(2,"李四",19));
list.add(new Student(3,"王五",18));
//把java集合对象转换成json格式字符串
String jsonString = JSONArray.toJSONString(list);
System.out.println(jsonString);//[{"age":20,"id":1,"name":"张三"},{"age":19,"id":2,"name":"李四"},{"age":18,"id":3,"name":"王五"}]
//把json格式字符串转换成java集合对象
List<Student> studentList = JSONArray.parseArray(jsonString, Student.class);
System.out.println(studentList);//[Student{id=1, name='张三', age=20}, Student{id=2, name='李四', age=19}, Student{id=3, name='王五', age=18}]
}
map
public static void main(String[] args) {
Map<String, Student> map = new HashMap<>();
map.put("张三", new Student(1, "张三", 20));
map.put("李四", new Student(2, "李四", 21));
map.put("王五", new Student(3, "王五", 22));
/*
map.forEach((o1,o2)->{
System.out.println(o1+o2);
});
*/
//把java的map类型转换成json格式字符串
String jsonString = JSON.toJSONString(map);
System.out.println(jsonString);//{"李四":{"age":22,"id":3,"name":"李四"},"张三":{"age":20,"id":1,"name":"张三"}}
//把json格式字符串转换成java的map类型
Map<String,Student> studentMap = JSON.parseObject(jsonString, Map.class);
System.out.println(studentMap);//{李四={"name":"李四","id":2,"age":21}, 张三={"name":"张三","id":1,"age":20}, 王五={"name":"王五","id":3,"age":22}}
}