User
import java.util.ArrayList;
import java.util.Arrays;
public class User {
private String name;
private int age;
private String[] hobby;
private ArrayList<Course> courses;
public User() {
}
public User(String name, int age, String[] hobby, ArrayList<Course> courses) {
this.name = name;
this.age = age;
this.hobby = hobby;
this.courses = courses;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
", hobby=" + Arrays.toString(hobby) +
", courses=" + courses +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String[] getHobby() {
return hobby;
}
public void setHobby(String[] hobby) {
this.hobby = hobby;
}
public ArrayList<Course> getCourses() {
return courses;
}
public void setCourses(ArrayList<Course> courses) {
this.courses = courses;
}
}
Course
public class Course {
private String math;
public Course() {
}
public String getMath() {
return math;
}
public void setMath(String math) {
this.math = math;
}
@Override
public String toString() {
return "Course{" +
"math='" + math + '\'' +
'}';
}
}
测试方法:
import com.alibaba.fastjson.JSONObject;
import org.junit.Test;
import java.util.ArrayList;
public class FashJson {
@Test
public void object2Json(){
ArrayList<Course> courses = new ArrayList<Course>();
for (int i = 0; i <3 ; i++) {
Course c = new Course();
c.setMath("数学"+i);
courses.add(c);
}
User user = new User("xxx", 25, new String[]{"篮球", "足球"}, courses);
String string = JSONObject.toJSONString(user);
System.out.println(string);
}
@Test
public void string2Object(){
String json="{\"age\":18,\"courses\":[{\"math\":\"数学0\"},{\"math\":\"数学1\"},{\"math\":\"数学2\"}],\"hobby\":[\"篮球\",\"足球\"],\"name\":\"xxx\"}";
JSONObject jsonObject = JSONObject.parseObject(json);
User user = JSONObject.parseObject(json, User.class);
System.out.println(user);
//User user = (User)jsonObject;
//System.out.println(jsonObject.get("name"));
}
}
个人总结:
在json字符串转对象时,需使用JSONObject.parseObject(String,class)的方法.
在对象转json字符串时,使用JSONObject.toJSONString(对象)的方法.