@Test
public void JSONStringTOJSONObject(){
JSONObject jsonObject = JSON.parseObject(COMPLEX_JSON_STR);
// 获取简单对象
String teacherName = jsonObject.getString(“teacherName”);
Integer teacherAge = jsonObject.getInteger(“teacherAge”);
System.out.println("teacherName: " + teacherName + ",teacherAge " + teacherAge);
// 获取JSONObject对象
JSONObject course = jsonObject.getJSONObject(“course”);
// 获取JSONObject中的数据
String courseName = course.getString(“courseName”);
Integer code = course.getInteger(“code”);
System.out.println("courseName: " + courseName + " code: " + code);
// 获取JSONArray对象
JSONArray students = jsonObject.getJSONArray(“students”);
// 获取JSONArray的中的数据
Iterator iterator = students.iterator();
while (iterator.hasNext()){
JSONObject jsonObject1 = (JSONObject) iterator.next();
System.out.println("studentName: " + jsonObject1.getString(“studentName”) + ",StudentAge: "
- jsonObject1.getInteger(“studentAge”));
}
}
用JSON.toJSONString()方法即可将复杂JSONObject转化为JSON字符串
/**
- 复杂JSONObject到json字符串的转换
*/
@Test
public void JSONObjectTOJSON(){
JSONObject jsonObject = JSON.parseObject(COMPLEX_JSON_STR);
String s = JSON.toJSONString(jsonObject);
System.out.println(s);
}
定义JavaBean类
package com.fastjson;
public class Student {
private String studentName;
private int studentAge;
public Student() {
}
public Student(String studentName, int studentAge) {
this.studentName = studentName;
this.studentAge = studentAge;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public int getStudentAge() {
return studentAge;
}
public void setStudentAge(int studentAge) {
this.studentAge = studentAge;