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

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;

    ...
}
4

1 に答える 1

3

読み込もうとしているオブジェクトに対応しない JSON を読み込もうとしています。具体的にはstudentList、JSON の値はオブジェクトです。

{
    "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 に答える