【发布时间】:2015-06-16 09:43:04
【问题描述】:
我正在为我的 android 应用程序使用带有 Gson 的 Retrofit 我有两个类:
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 数组。我怎样才能达到这个结果?
【问题讨论】:
-
如果 Retrofit 为我把所有东西都映射成“对象”,我会哭的。 Rest API 真的那么未定义吗?
-
你可以指定预期的类型和 gson 使用它