Gson 反序列化映射<String, List<SomeType>>
Gson Deserilize Map<String, List<SomeType>>
我正在为我的 android 应用程序使用 Gson 的 Retrofit 我有两个 class:
SomeClass1{
private Map<String, String> someMap;
private String otherProperty1;
private String otherProperty2;
}
SomeClass2{
private Map<String, Object> someMap;
private String otherProperty;
}
我有 <Map<String, Object>>
的 JsonDeserializer:
@Override
public Map<String, Object> deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
Gson gson = new Gson();
JsonObject jsonObject = json.getAsJsonObject();
Map<String, Object> result = new HashMap<String, Object>();
Iterable<Entry<String,JsonElement>> entries = jsonObject.entrySet();
for (Entry<String, JsonElement> entry : entries) {
result.put(entry.getKey(), gson.fromJson(entry.getValue(), Object.class) );
}
return result;
}
问题是:
当我从 json 获得 SomeClass2 对象时,其中 someMap
包含 <String, SomeClass1>
,它工作完美,但如果 someMap
包含 <String, List<SomeClass1>>
它给了我LinkedMapTree 数组而不是 SomeClass1 数组。我怎样才能达到这个结果?
试试这个:
result.put(entry.getKey(), gson.fromJson(entry.getValue(), List.class) );
我正在为我的 android 应用程序使用 Gson 的 Retrofit 我有两个 class:
SomeClass1{
private Map<String, String> someMap;
private String otherProperty1;
private String otherProperty2;
}
SomeClass2{
private Map<String, Object> someMap;
private String otherProperty;
}
我有 <Map<String, Object>>
的 JsonDeserializer:
@Override
public Map<String, Object> deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
Gson gson = new Gson();
JsonObject jsonObject = json.getAsJsonObject();
Map<String, Object> result = new HashMap<String, Object>();
Iterable<Entry<String,JsonElement>> entries = jsonObject.entrySet();
for (Entry<String, JsonElement> entry : entries) {
result.put(entry.getKey(), gson.fromJson(entry.getValue(), Object.class) );
}
return result;
}
问题是:
当我从 json 获得 SomeClass2 对象时,其中 someMap
包含 <String, SomeClass1>
,它工作完美,但如果 someMap
包含 <String, List<SomeClass1>>
它给了我LinkedMapTree 数组而不是 SomeClass1 数组。我怎样才能达到这个结果?
试试这个:
result.put(entry.getKey(), gson.fromJson(entry.getValue(), List.class) );