JSON with GSON

Google has made a wonderful library called GSON that can convert any JSON into a class and vice versa. As an Android developer you may come across a situation to Parse a JSON and show its result in your app often. You can achieve this parsing by writing a separate JSON Parser class and achieve it. But it is not a good idea to write JSON parser class for different types of JSON you may face in your app. Hence by using GSON you are in no need to worry about JSON parsing at all. Here I may discuss how to use GSON open source library to achieve our task.

Step 1
Download the latest .zip of GSON library and include .jar in your libs/ folder of your project.

Step 2

This method will parse the JSON and result will be converted as per the given target class.

public static <T> T parseResponseUsingGSON(String response, Class<T> targetClass) {
Gson gson = new Gson();
T responseObj = null;
try {
responseObj = gson.fromJson(response, targetClass);
} catch(JsonSyntaxException e) {
e.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}
return responseObj;
}

Step 3

Create a POJO class with required getters and setters of its fields. For example if your JSON response is

{
"data": {
"a": "apple",
"b": "ball",
"c": "cat"
}
}

Resulting POJO class will be as like this.

Dummy.java

public class Dummy {
//as per the JSON
Result data;
/**
* @return the data
*/
public Result getData() {
return data;
}
/**
* @param data the data to set
*/
public void setData(Result data) {
this.data = data;
}
}

and the Result.java is

public class Result {
//as per the JSON
String a,b;
/**
* @return the a
*/
public String getA() {
return a;
}

/**
* @param a the a to set
*/
public void setA(String a) {
this.a = a;
}

/**
* @return the b
*/
public String getB() {
return b;
}

/**
* @param b the b to set
*/
public void setB(String b) {
this.b = b;
}

If you plan to re name the field of the POJO then you should include the following annotation above the field declaration.

@SerializedName("data")
Result myData;

Based upon the resulting JSON one can design the POJO class. After receiving the JSON from server it can be parse using the above mentioned method “parseResponseUsingGSON”, for example

Dummy dClass =  parseResponseUsingGSON(jsonStringFromServer,Dummy.java);

Hence JSON is converted to POJO class.

Advertisements