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 }, } ] "]