FastJson的简单案例

User

import java.util.ArrayList;
import java.util.Arrays;

public class User {
    private String name;
    private int age;
    private String[] hobby;
    private ArrayList courses;

    public User() {
    }

    public User(String name, int age, String[] hobby, ArrayList 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 getCourses() {
        return courses;
    }

    public void setCourses(ArrayList 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 courses = new ArrayList();
        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(对象)的方法.

你可能感兴趣的:(FastJson的简单案例)