一、准备工作
定义三个json字符串用于以下测试:
//json字符串-简单对象
String jsonStr = "{\"studentName\":\"张三\",\"studentAge\":18}";
//json字符串-数组类型
String jsonArrStr = "[{\"studentName\":\"张三\",\"studentAge\":18},{\"studentName\":\"李四\",\"studentAge\":17}]";
//json字符串-复杂对象
String complexJsonStr= "{\"teacherName\":\"李寻欢\",\"teacherAge\":30,\"course\":{\"courseName\":\"武术\",\"code\":110},
\"students\":[{\"studentName\":\"张三\",\"studentAge\":18},{\"studentName\":\"李四\",\"studentAge\":19}]}";
二、json字符串、json对象、java对象的转换方法
1.JSON字符串到JSON对象的转换
(1)json字符串-简单对象与JSONObject之间的转换
JSONObject jsonObj = JSON.parseObject(jsonStr);
(2)json字符串-数组类型与JSONArray之间的转换
JSONArray jsonArray = JSON.parseArray(jsonArrStr);
//遍历JSONArray方法1
for(int i = 0; i < jsonArray.size(); i++){
JSONObject jsonObj = jsonArray.getJSONObject(i);
}
//遍历JSONArray方法2
for(Object obj : jsonArray){
JSONObject jsonObject = (JSONObject) obj;
}
(3)json字符串-复杂对象与JSONObject之间的转换
JSONObject jsonObj = JSON.parseObject(complexJsonStr);
//取出复杂对象中各项内容
String teacherName = jsonObj.getString("teacherName");
Integer teacherAge = jsonObj.getInteger("teacherAge");
JSONObject course = jsonObj.getJSONObject("course");
JSONArray students = jsonObj.getJSONArray("students");
2.JSON对象到JSON字符串的转换
JSONObject jsonObj = new JSONObject();
//JSONObject到JSON字符串的转换
String jsonStr = jsonObj.toJSONString();
3.JSON字符串到Java对象的转换
JSON字符串与JavaBean之间的转换建议使用TypeReference类
(1)json字符串-简单对象与Java对象之间的转换
// 方法1
Student student = JSON.parseObject(jsonStr , new TypeReference<Student>() {});
// 方法2
Student student = JSON.parseObject(jsonStr , Student.class);
(2)json字符串-数组与Java对象之间的转换
ArrayList<Student> students = JSON.parseObject(jsonArrStr, new TypeReference<ArrayList<Student>>() {});
for (Student student : students) {
System.out.println(student.getStudentName()+":"+student.getStudentAge());
}
(3)json字符串-复杂对象与Java对象之间的转换
Teacher teacher = JSON.parseObject(complexJsonStr, new TypeReference<Teacher>() {});
//获取teacher中的内容
String teacherName = teacher.getTeacherName();
Integer teacherAge = teacher.getTeacherAge();
Course course = teacher.getCourse();
List<Student> students = teacher.getStudents();
4.Java对象到JSON字符串的转换
Teacher teacher = new Teacher();
String jsonStr = JSON.toJSONString(teacher);
5.Java对象到JSON对象的转换
String jsonStr= JSON.toJSONString(student);
JSONObject jsonObj = JSON.parseObject(jsonStr);
6.JSON对象到Java对象的转换
# 方法1,先转换为json字符串,再使用parseObject
String jsonStr = jsonObj.toJSONString();
Student stu = JSON.parseObject(jsonStr,new TypeReference<Student>() {});
# 方法2,直接使用toJavaObject
Student stu = JSON.toJavaObject(jsonObj, Student.class);