Skip to main content

GSON Examples - Parse and Create JSON

GSON is a library provided by Google to convert Java Objects into their JSON representation and vice versa. This library is widely used in Android development for parsing JSON data from APIs and converting them into Java Objects.

Uses of Gson

  1. Conversion of Java Objects into JSON and back.
  2. Conversion of a JSON string to an equivalent Java object.

Why Gson was Created

Here are reasons for creation of Gson:

  1. To make working with JSON easy by providing simple toJson() and fromJson() methods. These methods allow us convert Java objects to JSON and vice-versa.
  2. To allow pre-existing unmodifiable objects to be converted to and from JSON.
  3. To provide Extensive support of Java Generics.
  4. To allow custom representations for objects
  5. To provide support for arbitrarily complex objects (with deep inheritance hierarchies and extensive use of generic types)

In this article, we will discuss how to use the GSON library in your Android project and use it to parse JSON data.

Step 1: Add GSON Library Dependency

To use GSON in your Android project, you need to add its dependency in the build.gradle file of your module. Add the following line to the dependencies section:

dependencies {
implementation 'com.google.code.gson:gson:2.8.6'
}

This will download the GSON library to your project and make it available for use.

Step 2: Create a Java Class for JSON Data

Before we can parse the JSON data using GSON, we need to create a Java class that will represent the structure of the JSON data. This class should have the same field names as the JSON keys and their corresponding data types.

For example, consider the following JSON data:

{
"name": "John Doe",
"age": 30,
"email": "john.doe@example.com"
}

We can create a Java class for this data as follows:

public class User {
private String name;
private int age;
private String email;

public String getName() {
return name;
}

public int getAge() {
return age;
}

public String getEmail() {
return email;
}
}

Note that the field names in the Java class should match the JSON keys exactly.

Step 3: Parse JSON Data using GSON

With the GSON library and Java class in place, we can now parse the JSON data using GSON. The following code snippet shows how to parse the JSON data into a User object:

String json = "{ \"name\": \"John Doe\", \"age\": 30, \"email\": \"john.doe@example.com\" }";
Gson gson = new Gson();
User user = gson.fromJson(json, User.class);

The fromJson method takes two parameters: the JSON data as a String, and the class that represents the structure of the data. It returns an object of the specified class with the data populated from the JSON string.

Step 4: Use Parsed Data

Now that we have the User object populated with the data from the JSON string, we can use it in our app as needed. For example, we can display the user's name in a TextView as follows:

TextView nameTextView = findViewById(R.id.name_text_view);
nameTextView.setText(user.getName());

Important Classes

(a) Gson

Gson is a class found in com.google.gson package and is the main class we need to use Gson Library.

Normally we use it first by first constructing a Gson instance and then invoking toJson(Object) or fromJson(String, Class) methods on it.

(b). JsonElement

JsonElement is a class found in com.google.gson package that represents an element of Json.

Here are JsonElement Objects:

  1. JsonObject
  2. JsonArray
  3. JsonPrimitive
  4. JsonNull.

(c) JsonObject

JsonObject is a class found in com.google.gson package that represents an object type in Json.

This object can comprise name-value pairs where names are strings, and values are any other type of JsonElement.

With this then we can build a tree of JsonElements. Those elements are maintained in order they were added.

(d) JsonParser

JsonParser is a class found in com.google.gson package that is used to parse Json into a parse tree of JsonElements

Creating Gson

1. Gson()

The first way of creating or constructing Gson object is to use the defalu constructor: Gson().

This will construct us a Gson object with default configuration.

That default configuration has the following settings:

  1. The JSON generated by toJson methods is in compact representation. This means that all the unneeded white-space is removed. You can change this behavior with GsonBuilder#setPrettyPrinting().
  2. The generated JSON omits all the fields that are null. Note that nulls in arrays are kept as is since an array is an ordered list. Moreover, if a field is not null, but its generated JSON is empty, the field is kept. You can configure Gson to serialize null values by setting GsonBuilder#serializeNulls().
  3. Gson provides default serialization and deserialization for Enums, Map, java.net.URL, java.net.URI, java.util.Locale, java.util.Date, java.math.BigDecimal, and java.math.BigInteger classes.

2. GsonBuilder

GsonBuilder can be used to instantiate Gson with various configuration settings.

Gson gson = new GsonBuilder().setPrettyPrinting().create();

GsonBuilder follows the builder pattern, and it is typically used by first invoking various configuration methods to set desired options, and finally calling the create() method.

Important Gson methods

(a). toJson()

This method serializes the specified object, including those of generic types, into its equivalent Json representation.

Gson gson = new Gson();
gson.toJson(map);

It must be used if the specified object is a generic type. For non-generic objects, use toJson(Object,Appendable) instead.

(b). fromJson

This method deserializes the specified Json into an object of the specified type. This method is useful if the specified object is a generic type. For non-generic objects, use fromJson(String,Class) instead.

If you have the Json in a Reader instead of a String, use fromJson(Reader,Type) instead.

(c). toJsonTree

This method serializes the specified object, including those of generic types, into its equivalent representation as a tree of JsonElements. This method must be used if the specified object is a generic type. For non-generic objects, use toJsonTree(Object)instead.

(d). getAdapter

Returns the type adapter for type.

Full Gson Hello World Example

Let's see a full Gson hello world example. You can copy paste this example into your IDE as long as you have Gson installed and run.

import com.google.gson.Gson;

/**
* Gson Hello World
*
*/
public class GsonHelloWorld {

public static void main(String[] args) {
// init class
Place place = new Place();
place.setName("World");

Human human = new Human();
human.setMessage("Hi");
human.setPlace(place);

// convert to json
Gson gson = new Gson();
String jsonString = gson.toJson(human);
System.out.println("json " + jsonString); // print "json {"message":"Hi","place":{"name":"World"}}"

// convert from json
Human newHuman = gson.fromJson(jsonString, Human.class);
newHuman.say(); // print "Hi , World!"
}

private static class Human {
private String message;
private Place place;

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}

public Place getPlace() {
return place;
}

public void setPlace(Place place) {
this.place = place;
}

public void say() {
System.out.println();
System.out.println(getMessage() + " , " + getPlace().getName() + "!");
}
}

private static class Place {
private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}
}

Quick GSON Examples and How To's

In these examples we are using Google Gson.

1. How to Convert Map to JSON

Suppose I give you a map with a String key and a T value. And I tell you to map it or convert to a JSON string.

How would you do it?

Well you can simply use the toJson() method of Gson class. You first have to instantiate that Gson class then invoke that method.

    public static <T> String mapToJsonStr(Map<String, T> map) {
Gson gson = new Gson();
return gson.toJson(map);
}

2. How to Convert JSON to Map

What about if you have JSON String and we ask you to convert it to a Map data structure in java.

Well then you would use Gson's fromJson() method.

However this time you must instantiate a TypeToken with that Map as a generic parameter. Then pass the json string as our first parameter in the fromJson() method. And the Type instance as our second parameter.

    public static <T> Map<String, T> jsonStrToMap(String jsonStr) {
Gson gson = new Gson();
Type type = new TypeToken<Map<String, T>>() {
}.getType();
return gson.fromJson(jsonStr, type);
}

3. How to Convert JSON to Object

All right you have a JSON String and you are told to convert it to an Object of given type.

Well, again you pass the json string and the type to the fromJson() method.

    public static <T> T jsonToObj(String jsonStr, Class<T> classOfT) {
return new Gson().fromJson(jsonStr, classOfT);
}

4. How to Convert JSON to ArrayList

A common scenario in many projects is to convert a json string to an ArrayList, the most commonly used collection.

We start by using the TextUtils' isEmpty() method to check for empty values.

Then we obtain our TypeToken instance with ArrayList of JSONObjects passed as our generic type.

Then use the fromJson() method to get our ArrayList of JSONObjects.

Then now we can loop through it and to fill the ArrayList that we want to populate.

    public static <T> ArrayList<T> jsonToArrayList(String json, Class<T> clazz) {
if (TextUtils.isEmpty(json)) {
return null;
}
Type type = new TypeToken<ArrayList<JsonObject>>() {
}.getType();
ArrayList<JsonObject> jsonObjects = new Gson().fromJson(json, type);

ArrayList<T> arrayList = new ArrayList<>();
for (JsonObject jsonObject : jsonObjects) {
arrayList.add(new Gson().fromJson(jsonObject, clazz));
}
return arrayList;
}

5. How to Convert List to JSON

Another common thing is to convert a List to a json string. Maybe you want to serialize that list and send it over the where or a basic way of exposing it as an API.

Again, the toJson() method easily does that for us.

    public static <T> String listToJson(List<T> list) {

Gson gson = new Gson();
String jsonstring = gson.toJson(list);
return jsonstring;

}

6. How to Convert Object to JSON

You have an object and you should convert it to JSON, well you simply invoke the toJson() method with the object passed as a parameter.

    public static <T> String object2Json(T t) {
Gson gson = new Gson();
return gson.toJson(t);
}

7. How to exclude specific fields from Serialization without annotations

Normally you control fields to include via annotations in Gson. However, can we do it without annotations.

Gson gson = new GsonBuilder()
.setExclusionStrategies(new TestExclStrat())
//.serializeNulls() <-- uncomment to serialize NULL fields as well
.create();
Student src = new Student();
String json = gson.toJson(src);
System.out.println(json);

Reference

8. How to Pretty Print with Gson

PrettyPrinting means adding white-space to make our JSON data more readable. You can use GsonBuilder#setPrettyPrinting().

Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(uglyJSONString);
String prettyJsonString = gson.toJson(je);

Reference

9. How to write JSON using TreeModel

Here's the important method. We have two methods for reading and writing json data.

Here's the full class:


import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.IOException;

public class TreeModel {
public static void main(String[] args) throws IOException {
System.out.print("readJson: ");
readJson();
System.out.println();
System.out.print("writeJson: ");
writeJson();
}

/**
* Example to readJson using TreeModel
*/
private static void readJson() throws IOException {
JsonParser parser = new JsonParser();
JsonElement jsonElement = parser.parse("{"message":"Hi","place":{"name":"World!"}}");
JsonObject rootObject = jsonElement.getAsJsonObject();
String message = rootObject.get("message").getAsString(); // get property "message"
JsonObject childObject = rootObject.getAsJsonObject("place"); // get place object
String place = childObject.get("name").getAsString(); // get property "name"
System.out.println(message + " " + place); // print "Hi World!"*/
}

/**
* Example to writeJson using TreeModel
*/
private static void writeJson() throws IOException {
JsonObject rootObject = new JsonObject();
rootObject.addProperty("message", "Hi");
JsonObject childObject = new JsonObject();
childObject.addProperty("name", "World!");
rootObject.add("place", childObject);

Gson gson = new Gson();
String json = gson.toJson(rootObject);
System.out.println(json); // print "{"message":"Hi","place":{"name":"World!"}}"
}
}

10. How to Convert String to Object

Gson myGson = new GsonBuilder().setPrettyPrinting().create();
myGson.fromJson(jsonString, Person.class)

11. Pretty Printing JSON String

private static String pretty(String json) {
JsonElement gson = new JsonParser().parse(json);
return new GsonBuilder().setPrettyPrinting().serializeNulls().create().toJson(gson);
}
}

12. Streaming API Read and Write using Gson

This is an example of JSON Streaming API reading and writing. We will use JsonReader, JsonToken and JsonWriter classes.

We have three methods, our main() method, a readJSON() method and writeJson() method.

import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;

import java.io.*;
import java.nio.charset.Charset;

public class StreamingAPI {
public static void main(String[] args) throws IOException {
System.out.print("readJson: ");
readJson();
System.out.println();
System.out.print("writeJson: ");
writeJson();
}

/**
* Example to readJson using StreamingAPI
*/
private static void readJson() throws IOException {
String str = "{"message":"Hi","place":{"name":"World!"}}";
InputStream in = new ByteArrayInputStream(str.getBytes(Charset.forName("UTF-8")));
JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
while (reader.hasNext()) {
JsonToken jsonToken = reader.peek();
if(jsonToken == JsonToken.BEGIN_OBJECT) {
reader.beginObject();
} else if(jsonToken == JsonToken.END_OBJECT) {
reader.endObject();
} if(jsonToken == JsonToken.STRING) {
System.out.print(reader.nextString() + " "); // print Hi World!
} else {
reader.skipValue();
}
}
reader.close();
}

/**
* Example to writeJson using StreamingAPI
*/
private static void writeJson() throws IOException {
OutputStream outputStream = new ByteArrayOutputStream();
JsonWriter writer = new JsonWriter(new OutputStreamWriter(outputStream, "UTF-8"));
writer.beginObject(); // main object
writer.name("message");
writer.value("Hi");
writer.name("place"); // save object Place
writer.beginObject();
writer.name("name");
writer.value("World!");
writer.endObject();
writer.endObject();
writer.close();
System.out.println(outputStream.toString()); // print "{"message":"Hi","place":{"name":"World!"}}"
}
}

13. Full Reusable Gson Utility class

ublic class GsonUtils {

privatestaticfinaldoubleVERSION=1.0f;
private static final Gson sGson = createGson(true, false);

private static final Gson sGsonExpose = createGson(true, true);

private GsonUtils () {
thrownewAssertionError();
}

/**
* Create the standard {@link Gson} configuration
*
* @return created gson, never null
*/
public static Gson createGson() {
return createGson(true, false);
}

/**
* Create the standard {@link Gson} configuration
*
* @param serializeNulls whether nulls should be serialized
* @return created gson, never null
*/
private static Gson createGson(final boolean serializeNulls,
final boolean exposeEnable ) {
final GsonBuilder builder = new GsonBuilder ();
if (serializeNulls) {
builder.serializeNulls();
}
builder . setVersion ( VERSION );
// json format
// builder.setPrettyPrinting();
if (exposeEnable) {
builder.excludeFieldsWithoutExposeAnnotation();
}
return builder.create();
}

/**
* Get reusable pre-configured {@link Gson} instance
*
* @return Gson instance
*/
public static Gson getGson() {
return sGson;
}

/**
* Get reusable pre-configured {@link Gson} instance
*
* @return Gson instance
*/
public static Gson getGson(final boolean exposeEnable) {
return exposeEnable ? sGsonExpose : sGson;
}

/**
* Convert object to json, only exports attributes that have been annotated with @Expose
*
* @param object
* @return json string
*/
public static String toJson(final Object object) {
return toJson(object, true);
}

/**
* Convert object to json
*
* @param object
* @param exposeEnable Whether to export only @Expose annotated properties, true is only exported by @Expose
* @return json string
*/
public static String toJson(final Object object,
final boolean exposeEnable ) {
return exposeEnable ? sGsonExpose.toJson(object) : sGson.toJson(object);
}

/**
* Convert string to given type
*
* @param json
* @param type
* @return instance of type
*/
public static <V> V fromJson(String json, Class<V> type) {
return sGson.fromJson(json, type);
}

/**
* Convert string to given type
*
* @param json
* @param type
* @return instance of type
*/
public static <V> V fromJson(String json, Type type) {
returnsGson.fromJson(json,type);
}

/**
* Convert content of reader to given type
*
* @param reader
* @param type
* @return instance of type
*/
public static <V> V fromJson(Reader reader, Class<V> type) {
return sGson.fromJson(reader, type);
}

/**
* Convert content of reader to given type
*
* @param reader
* @param type
* @return instance of type
*/
public static <V> V fromJson(Reader reader, Type type) {
returnsGson.fromJson(reader,type);
}

/**
* Convert object object to map only supports basic types
*
* @param src
* @param exposeEnable
* @return
*/
public static HashMap<String, String> toMap(Object src, boolean exposeEnable) {
Gson gson = exposeEnable ? sGsonExpose : sGson;
HashMap<String, String> params = new HashMap<String, String>();
try {
if (src == null) {
return null;
}
JsonElement jsonTree = gson . toJsonTree ( src );
JsonObject jsonObj = jsonTree.getAsJsonObject();
Iterator<Entry<String, JsonElement>> iterator = jsonObj.entrySet().iterator();
String curKey;
JsonElement curVal ;
while (iterator.hasNext()) {
Entry<String, JsonElement> entry = iterator.next();
curKey = entry.getKey();
curVal = entry.getValue();
if (!curVal.isJsonNull()) {
params.put(curKey, curVal.getAsString());
}
}
return params;
} Catch ( Exception e ) {
e . printStackTrace ();
}
returnparams;
}

public static <T> String mapToJson(Map<String, T> map) {
Gson gson = new Gson ();
return gson . toJson (folder);
}
}

Conclusion

In this article, we learned how to use the GSON library in an Android project and use it to parse JSON data. We also saw how to create a Java class that represents the structure of the JSON data and use it to parse the data into an object. With GSON, parsing JSON data in Android apps has never been easier.