JsonParseException:无法反序列化JSON

时间:2013-10-16 04:25:01

标签: java json gson

尝试反序列化此JSON字符串时,我遇到以下异常:

{ "studentName": "John", "studentAge": "20" }

例外:

com.google.gson.JsonParseException: The JsonDeserializer com.google.gson.DefaultTypeAdapters$CollectionTypeAdapter@41d241d2 failed to deserialize json object { "studentName": "John", "studentAge": "20" } given the type java.util.List<...>
    at com.google.gson.JsonDeserializerExceptionWrapper.deserialize(JsonDeserializerExceptionWrapper.java:64)
    at com.google.gson.JsonDeserializationVisitor.invokeCustomDeserializer(JsonDeserializationVisitor.java:92)

这些是我的课程:

public class School {

    Gson gson = new Gson();
    String json = ...// I can read json from text file, the string is like { "className": "Math", "classTime": "2013-01-01 11:00", "studentList": { "studentName": "John", "studentAge": "20" }}
    CourseInfo bean = gson.fromJson(json,  CourseInfo.class);
}

CourseInfo.java:

public class CourseInfo implements Serializable {

    private static final long serialVersionUID = 1L;

    private String className;
    private Timestamp classTime;
    private List<StudentInfo> studentList;

    ...
}

StudentInfo.java

public class CourseInfo implements Serializable {

    private static final long serialVersionUID = 1L;

    private String studentName;
    private String studentAge;

    ...
}

1 个答案:

答案 0 :(得分:3)

您正在尝试阅读一些与您尝试将其读入的对象不对应的JSON。具体来说,JSON中的studentList值是一个对象:

{
    "studentName": "John",
    "studentAge": "20"
}

但是,您尝试将该对象读入列表。鉴于变量名为studentList,我猜测JSON是错误的,而不是你的代码,而且它应该是一个数组,而不是:

{
    "className": "Math",
    "classTime": "2013-01-01 11:00",
    "studentList": [
        {
            "studentName": "John",
            "studentAge": "20"
        }
    ]
}