解析使用Gson的json時出現問題。 這裏是我的代碼:使用Gson解析json java
Gson gson = new GsonBuilder().create();
String json = gson.toJson(myMap.values());
MyClass clazz = gson.fromJson(json, MyClass.class);
System.out.println(clazz.toString());
,但我得到了一個錯誤(我也試圖與新TypeToken,但錯誤是一樣的):
com.google.gson.JsonParseException: The JsonDeserializer MapTypeAdapter failed to deserialized json object /*here is json object*/
Caused by: java.lang.IllegalArgumentException: Map objects need to be parameterized unless you use a custom serializer. Use the com.google.gson.reflect.TypeToken to extract the ParameterizedType.
at com.google.gson.TypeInfoMap.<init>(TypeInfoMap.java:45)
at com.google.gson.DefaultTypeAdapters$MapTypeAdapter.deserialize(DefaultTypeAdapters.java:605)
at com.google.gson.DefaultTypeAdapters$MapTypeAdapter.deserialize(DefaultTypeAdapters.java:573)
at com.google.gson.JsonDeserializerExceptionWrapper.deserialize(JsonDeserializerExceptionWrapper.java:50)
這裏得到JSON字符串,它是有效的(但可能是我應該刪除「項目」子字符串?):
["{\n
\"items\":
[
\n {
\n \"MyClass_type_var1\": {
\n \"field1\": \"val1\",
\n \"field2\": \"val2\",
\n \"field3\": [
\n {
\n \"subfield1\": subval
\n }
\n ]
\n }
\n },
\n \"MyClass_type_var2\": {
\n \"field1\": \"val1\",
\n \"field2\": \"val2\",
\n \"field3\": [
\n {
\n \"subfield1\": subval
\n }
\n ]
\n }
\n },
\n \"MyClass_type_var3\": {
\n \"field1\": \"val1\",
\n \"field2\": \"val2\",
\n \"field3\": [
\n {
\n \"subfield1\": subval
\n }
\n ]
\n }
\n },
etc...... may I haven't closed brackets correctly, but they are correct :)
}
]
"]
我會感謝任何建議。
public final class MyClass extends GenericJson {
private String field1;
private String field2;
private java.util.List<AClass> field3; // has subfield1
//getters and setters
}
單行JSON:
["{\n \"items\": [ \n { \n \"MyClass\": { \n \"field1\": \"val1\", \n \"field2\": \"val2\", \n \"field2\": [ \n { \n \"subfield1\": subval \n } \n ] \n } \n }, \n \"MyClass\": { \n \"field1\": \"val1\", \n \"field2\": \"val2\", \n \"field2\": [ \n { \n \"subfield1\": subval \n } \n ] \n } \n }, \n \"MyClass\": {\n \"field1\":\"val1\", \n \"field2\": \"val2\", \n \"field2\": [ \n { \n \"subfield1\": subval \n } \n ] \n } \n }, } ] "]
你可以發佈MyClass。 – 2012-07-05 09:38:01
什麼是MyClass – 2012-07-05 09:41:47
添加MyClass代碼 – 2012-07-05 09:45:27