java - JsonParseException : Fail to Deserializer JSON

标签 java json gson

尝试反序列化此 JSON 字符串时出现以下异常:

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

异常(exception):

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)

这些是我的类(class):

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);
}

类(class)信息.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;

    ...
}

最佳答案

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

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

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

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

关于java - JsonParseException : Fail to Deserializer JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19395229/

相关文章:

java - Quarkus 是针对 docker 容器运行时优化的还是仅针对 Kubernetes

java - 如何在不运行方法的情况下模拟方法调用和返回值?

java - 通过 Rest 调用在我的 Java 类中获取 JSON 结果

java - Gson 使用 InstanceCreator 反序列化嵌套对象

java - 如何用Gson反序列化子类?

java - Spring MVC 中的@RequestParam 处理可选参数

java - 将图表插入内部 jframe

Java读取JSON输入流

javascript - 当缓存硬重新加载时,我的toggleClass函数有时仅适用于我的JSON创建的字段

java - 如何将 JsonArray 从 Gson 转换为流