1. 程式人生 > >fastjson解析json時報錯 class not has default constructor

fastjson解析json時報錯 class not has default constructor

在序列化用alibaba的json包把物件進行序列化的時候,總是報錯

Exception in thread "main" com.alibaba.fastjson.JSONException: default constructor not found. class com.mex.test.redis.Person

Person類

public class Person {

    private String name;
    private int age;



    public Person(String name, int age) {
        this
.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } }

User類

public class User {

    private String id;
    private List<Person> users = new ArrayList<Person>();


    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public List<Person> getUsers() {
        return users;
    }

    public
void setUsers(List<Person> users) { this.users = users; } }

測試類

public class SerializationTest {

    public static void main(String[] args) {

        User user = new User();
        user.setId("1001");
        Person p1 = new Person("xiaoming",23);
        Person p2 = new Person("jack",34);
        ArrayList<Person> pList = Lists.newArrayList();
        pList.add(p1);
        pList.add(p2);

        user.setUsers(pList);

        // 序列化
        String s = JSON.toJSONString(user);
        System.out.println(s);

        User user1 = JSON.parseObject(s, User.class);
        System.out.println(user1);
    }
}

查找了半天的資料,fastJson在反序列化的時候需要呼叫物件的預設構造方法,如果該物件之中還包含其他的物件,那麼都需要建立預設的無參構造方法。

解決方案:將User的預設無參構造和Person的預設無參構造補充到類中,即可。

public User() {
    }
public Person() {
    }

打印出來的資訊為:

{"id":"1001","users":[{"age":23,"name":"xiaoming"},{"age":34,"name":"jack"}]}
com.mex.test.redis.User@15f550a

Process finished with exit code 0