Android Handling JSON with Gson suggest change

Parsing JSON with Gson

The example shows parsing a JSON object using the Gson library from Google.

Parsing objects:

class Robot {
    //OPTIONAL - this annotation allows for the key to be different from the field name, and can be omitted if key and field name are same . Also this is good coding practice as it decouple your variable names with server keys name 
    private String version;

    private int age;
    private String name;
    // optional : Benefit it allows to set default values and retain them, even if key is missing from Json response. Not required for primitive data types. 

    public Robot{
       version = "";
       name = "";

Then where parsing needs to occur, use the following:

String robotJson = "{
                        \"version\": \"JellyBean\",
                        \"age\": 3,
                        \"robotName\": \"Droid\"

Gson gson = new Gson();
Robot robot = gson.fromJson(robotJson, Robot.class);

Parsing a list:

When retrieving a list of JSON objects, often you will want to parse them and convert them into Java objects.

The JSON string that we will try to convert is the following:

  "owned_dogs": [
      "name": "Ron",
      "age": 12,
      "breed": "terrier"
      "name": "Bob",
      "age": 4,
      "breed": "bulldog"
      "name": "Johny",
      "age": 3,
      "breed": "golden retriever"

This particular JSON array contains three objects. In our Java code we’ll want to map these objects to Dog objects. A Dog object would look like this:

private class Dog {
    public String name;
    public int age;

    public String breedName;

To convert the JSON array to a Dog[]:

Dog[] arrayOfDogs = gson.fromJson(jsonArrayString, Dog[].class);

Converting a Dog[] to a JSON string:

String jsonArray = gson.toJson(arrayOfDogs, Dog[].class);

To convert the JSON array to an ArrayList<Dog> we can do the following:

Type typeListOfDogs = new TypeToken<List<Dog>>(){}.getType();
List<Dog> listOfDogs = gson.fromJson(jsonArrayString, typeListOfDogs);

The Type object typeListOfDogs defines what a list of Dog objects would look like. GSON can use this type object to map the JSON array to the right values.

Alternatively, converting a List<Dog> to a JSON array can be done in a similar manner.

String jsonArray = gson.toJson(listOfDogs, typeListOfDogs);

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents
64 Menu
107 Handling JSON with Gson
112 Loader
119 Xposed
132 Colors
135 Fresco
140 AdMob
147 Button
156 Vk SDK
170 XMPP
176 OpenCV
200 FileIO
203 Moshi
217 Paint
231 AIDL
241 JCodec
243 Okio
255 Looper
  ↑ ↓ to navigate     ↵ to select     Esc to close