2013-10-16 33 views
0

嘗試反序列化這個JSON字符串時,我有以下異常:JsonParseException:失敗解串器JSON

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

例外:

com.google.gson.JsonParseException: The JsonDeserializer [email protected]d2 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; 

    ... 
} 

回答

3

您正在嘗試讀一些JSON不符合你試圖讀取到的對象。具體而言,在JSON的studentList值是一個對象:

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

但是,您試圖讀取該對象到一個列表。鑑於變量命名爲studentList,我猜想,JSON是錯誤的,而不是你的代碼,它應該是一個數組,而不是:

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

非常感謝!:) – LoveTW