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

猜你在找的Json相关文章