Parsing JSON with Gson

suggest change

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 
    @SerializedName("version") 
    private String version;

    @SerializedName("age")
    private int age;
    
    @SerializedName("robotName")
    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;

    @SerializedName("breed")
    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:

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


JSON handling with org.json:
* Parsing JSON with Gson

Table Of Contents
2 Gradle
5 Intent
6 JSON handling with org.json
17 Service
19 WebView
31 SQLite
35 Glide
37 Dialog
38 ACRA
44 Handler
53 Toast
63 Menu
65 Picasso
70 Volley
71 Widgets
78 Realm
90 Spinner
95 OkHttp
108 TextView
109 ListView
111 Loader
118 Xposed
119 Security
121 ImageView
123 Doze Mode
130 Drawables
131 Colors
134 Fresco
139 AdMob
145 Keyboard
146 Button
150 EditText
155 Vk SDK
163 ExoPlayer
169 XMPP
175 OpenCV
177 Threads
184 ORMLite
186 TabLayout
190 LruCache
192 Zip files
194 Fastlane
199 FileIO
202 Moshi
210 VideoView
216 Paint
218 ProGuard
226 CleverTap
228 ADB shell
229 Ping ICMP
230 AIDL
234 Context
240 JCodec
242 Okio
249 FuseView
254 Looper
261 Fastjson
263 Jackson
267 Smartcard