使用 Gson 解析 json 时遇到问题。这是我的代码:
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字符串,它是有效的(但可能我应该删除“items”子字符串?):
["{\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 }, } ] "]