0

尝试反序列化此 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);
}

课程信息.java:

public class CourseInfo implements Serializable {

    private static final long serialVersionUID = 1L;

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

    ...
}

学生信息.java

public class CourseInfo implements Serializable {

    private static final long serialVersionUID = 1L;

    private String studentName;
    private String studentAge;

    ...
}
4

1 回答 1

3

您正在尝试读取一些与您尝试读取的对象不对应的 JSON。具体来说,studentListJSON 中的值是一个对象:

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

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

{
    "className": "Math",
    "classTime": "2013-01-01 11:00",
    "studentList": [
        {
            "studentName": "John",
            "studentAge": "20"
        }
    ]
}
于 2013-10-16T04:29:19.570 回答