Gson Deserilize Map <string,list <sometype =“”>&gt;

时间:2015-06-16 09:43:05

标签: android gson retrofit

我使用Gtr的Retrofit为我的Android应用程序而且我有两个类:

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的Array。我怎样才能达到这个效果?

1 个答案:

答案 0 :(得分:0)

试试这个:

result.put(entry.getKey(), gson.fromJson(entry.getValue(), List.class) );