Skip to content

Instantly share code, notes, and snippets.

@rajohns08
Last active June 4, 2016 17:12
Show Gist options
  • Save rajohns08/62bd0bb4f8b9ac4e99b3d0edfaee1a01 to your computer and use it in GitHub Desktop.
Save rajohns08/62bd0bb4f8b9ac4e99b3d0edfaee1a01 to your computer and use it in GitHub Desktop.
Android / Java - Gson model object without making container object to unwrap root element

The following pattern helps to avoid making a PersonWrapper class that just has one property of Person the_person.

Use by calling

Person person = Person.fromJson(responseFromNetworkCall);

Example json you would be unwrapping seen in person.json.

public class Person {
public static class Container {
public Person the_person;
}
public static Person fromJson(String json) {
Gson gson = new Gson();
Person.Container container = gson.fromJson(json, Person.Container.class);
return container.the_person;
}
@SerializedName("id") public Integer id;
@SerializedName("first_name") public String firstName;
@SerializedName("middle_name") public String middleName;
@SerializedName("last_name") public String lastName;
}
{
"the_person": {
"id": 123,
"first_name": "robert",
"middle_name": "adam",
"last_name": "johns"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment