How would you like your model class to look?
status
and total
would probably be int
, so that only leaves info
.
As an experiment, just add a field Object info
and see how Gson would set it to an ArrayList<LinkedHashMap<String, String>>
-- ugly and hard to access by key, but all the data is there. Given that information, the fastest way to model a class would be:
class Something {
int status;
List<Map<String, String> info;
int total;
}
If you have control over how that JSON is generated, I suggest changing the structure of info
from an array of objects [{a:b},{c:d},{e:f}]
to just an object {a:b,c:d,e:f}
. With this, you could just map it to a Map<String, String>
with all the benefits like access by key, keys()
and values()
:
class Something {
int status;
Map<String, String> info;
int total;
}
If you want the latter model class without changing the JSON format, you'll have to write a TypeAdapter
(or JsonDeserializer
if you're only interested in parsing JSON, not generating it from your model class).
Here's a JsonDeserializer hat would map your original info
JSON property to a plain 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;
}
}
You need to register this custom JsonDeserializer
similar to this:
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(
new TypeToken<Map<String, String>>() {}.getType(),
new ArrayOfObjectsToMapDeserializer());
Gson gson = builder.create();
Note that this registers the custom deserializer for any Map<String, String>
regardless in what class it is encountered. If you don't want this, you'll need to create a custom TypeAdapterFactory
as well and check the declaring class before returning and instance of the deserializer.