I\'m consuming an API from my android app, and all the JSON responses are like this:
{
\'status\': \'OK\',
\'reason\': \'Everything was fine\',
\
This is the same solution as @AYarulin but assume the class name is the JSON key name. This way you only need to pass the Class name.
class RestDeserializer implements JsonDeserializer {
private Class mClass;
private String mKey;
public RestDeserializer(Class targetClass) {
mClass = targetClass;
mKey = mClass.getSimpleName();
}
@Override
public T deserialize(JsonElement je, Type type, JsonDeserializationContext jdc)
throws JsonParseException {
JsonElement content = je.getAsJsonObject().get(mKey);
return new Gson().fromJson(content, mClass);
}
}
Then to parse sample payload from above, we can register GSON deserializer. This is problematic as the Key is case sensitive, so the case of the class name must match the case of the JSON key.
Gson gson = new GsonBuilder()
.registerTypeAdapter(Content.class, new RestDeserializer<>(Content.class))
.build();