Parsing JSON with Gson
suggest changeThe example shows parsing a JSON object using the Gson library from Google.
Parsing objects:
class Robot {
// OPTIONAL. The annotation lets the key differ from the field name, and it can be omitted when they match.
@SerializedName("version")
private String version;
@SerializedName("age")
private int age;
@SerializedName("robotName")
private String name;
// Gson does not run this constructor. A missing key leaves an object field null and a primitive at 0 or false.
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"
}
]
}
The document above is an object. Its owned_dogs array contains three objects. In our Java code we'll want to map those objects to Dog objects. A Dog[] parses that array, not the whole document. 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);