我尝试使用customDeserilizer解析JSON以嵌套Object
这是我的解串器:
class MapDeserializer implements JsonDeserializer<Map<String, String>> {
public Map<String, String> deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context){
try {
Map<String, String> result = new HashMap<String, String>();
JsonObject object = json.getAsJsonObject();
for (Map.Entry<String, JsonElement> entry : object.entrySet()) {
String key = entry.getKey();
String value = entry.getValue().getAsString();
result.put(key, value);
}
// }
return result;
}catch (Exception e){
e.printStackTrace();
return null;
}
}
}
我正在使用以下代码行注册此解串器
Gson gson = new GsonBuilder().registerTypeHierarchyAdapter(TaggedActorMap.class, new MapDeserializer()).create();
sActivityBean = gson.fromJson(result,
SimilarActivityBean.class);
这是我的POJO班级
public class TaggedActorMap implements Serializable {
private String key;
private String value;
}
我收到错误
java.lang.IllegalArgumentException: invalid value for field
at java.lang.reflect.Field.setField(Native Method)
at java.lang.reflect.Field.set(Field.java:588)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1
.read(ReflectiveTypeAdapterFactory.java:119)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter
.read(ReflectiveTypeAdapterFactory.java:217)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.
read(TypeAdapterRuntimeTypeWrapper.java:40)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.
read(CollectionTypeAdapterFactory.java:81)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.
read(CollectionTypeAdapterFactory.java:60)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.
read(ReflectiveTypeAdapterFactory.java:117)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.
read(ReflectiveTypeAdapterFactory.java:217)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.
read(ReflectiveTypeAdapterFactory.java:117)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter
.read(ReflectiveTypeAdapterFactory.java:217)
at com.google.gson.Gson.fromJson(Gson.java:814)
at com.google.gson.Gson.fromJson(Gson.java:779)
at com.google.gson.Gson.fromJson(Gson.java:728)
at com.google.gson.Gson.fromJson(Gson.java:700)
答案 0 :(得分:0)
这有点乱。你需要确保一切都捆绑在一起。
您并未在任何地方提及MapSerializer
(您的JsonDeserializer
实施)。在构建ArrayOfObjectsToMapDeserializer
时,您指的是名为GsonBuilder
的内容。此外,在构建构建器时,请参考TaggedActorMap.class
,但您正在尝试反序列化名为SimilarActivityBean
的类。
您尚未为SimilarActivityBean
注册任何自定义反序列化程序,因此我猜测gson尝试使用某些默认反序列化程序反序列化JSON,但由于实际JSON中的数据与{中的字段不匹配,因此失败{1}}