You must write your own deserializer that returns an inline object.
Let's say your JSON is:
{ "status":"OK", "reason":"some reason", "content" : { "foo": 123, "bar": "some value" } }
Then you will have Content POJO:
class Content { public int foo; public String bar; }
Then you write the deserializer:
class MyDeserializer implements JsonDeserializer<Content> { @Override public Content deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) throws JsonParseException {
Now, if you are Gson using GsonBuilder and register a deserializer:
Gson gson = new GsonBuilder() .registerTypeAdapter(Content.class, new MyDeserializer()) .create();
You can deserialize your JSON directly to your Content :
Content c = gson.fromJson(myJson, Content.class);
Edit to add from comments:
If you have different types of messages, but they all have a βcontentβ field, you can make a universal deserializer by doing:
class MyDeserializer<T> implements JsonDeserializer<T> { @Override public T deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) throws JsonParseException {
You just need to register an instance for each of your types:
Gson gson = new GsonBuilder() .registerTypeAdapter(Content.class, new MyDeserializer<Content>()) .registerTypeAdapter(DiffContent.class, new MyDeserializer<DiffContent>()) .create();
When you call .fromJson() type is transferred to the deserializer, so it should work for all of your types.
And finally, when creating the Retrofit instance:
Retrofit retrofit = new Retrofit.Builder() .baseUrl(url) .addConverterFactory(GsonConverterFactory.create(gson)) .build();