您希望您的模型类看起来如何?
status
和total
可能是int
,所以只留下info
。
作为一个实验,只需添加一个字段Object info
,看看GSON将其设置为ArrayList<LinkedHashMap<String, String>>
- 丑陋不堪,通过密钥访问,但所有的数据是存在的。鉴于信息,一类模型的最快方法是:
class Something {
int status;
List<Map<String, String> info;
int total;
}
如果你有过怎样的生成JSON,我建议从对象[{a:b},{c:d},{e:f}]
只是一个对象{a:b,c:d,e:f}
数组改变info
结构控制。
class Something {
int status;
Map<String, String> info;
int total;
}
如果你想在不改变JSON格式,后者模型类,你必须写:有了这个,你可以只将其与所有喜欢的密钥访问,keys()
和values()
好处映射到Map<String, String>
一个TypeAdapter
(或JsonDeserializer
,如果你只是感兴趣的解析JSON,而不是从你的模型类生成它)。
这里有一个JsonDeserializer帽子将您的原始info
JSON属性映射到一个普通的Map<String, String>
。
class ArrayOfObjectsToMapDeserializer
implements JsonDeserializer<Map<String, String>> {
public Map<String, String> deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
Map<String, String> result = new HashMap<String, String>();
JsonArray array = json.getAsJsonArray();
for (JsonElement element : array) {
JsonObject object = element.getAsJsonObject();
// This does not check if the objects only have one property, so JSON
// like [{a:b,c:d}{e:f}] will become a Map like {a:b,c:d,e:f} as well.
for (Entry<String, JsonElement> entry : object.entrySet()) {
String key = entry.getKey();
String value = entry.getValue().getAsString();
result.put(key, value);
}
}
return result;
}
}
您需要注册与此类似这种风俗JsonDeserializer
:
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(
new TypeToken<Map<String, String>>() {}.getType(),
new ArrayOfObjectsToMapDeserializer());
Gson gson = builder.create();
注意不管此注册了任何Map<String, String>
自定义解串器中遇到什么课了。如果你不想要这个,你还需要创建一个自定义的TypeAdapterFactory
,然后在返回之前检查声明类以及解串器的实例。
键怎么来是动态的?我认为键的内容可以是动态的...你是否自己手动生成json字符串...? – waqaslam 2012-04-22 12:06:22