GSON Examples - Parse and Create JSON
Android Google Gson Examples and Tutorials.
Gson (also known as Google Gson) is a small Java-based library for parsing and creating JSON objects.
It's a serialization/deserialization library to convert Java Objects into JSON and back.
Google developed Gson for its own projects, but later made Gson publicly available, starting with version 1.0.
Gson is very powerful and is capable of working with arbitrary Java objects including pre-existing objects that you do not have source-code of.
Uses of Gson
- Conversion of Java Objects into JSON and back.
- Conversion of a JSON string to an equivalent Java object.
Why Gson was Created
Here are reasons for creation of Gson:
- To make working with JSON easy by providing simple
toJson()
andfromJson()
methods. These methods allow us convert Java objects to JSON and vice-versa. - To allow pre-existing unmodifiable objects to be converted to and from JSON.
- To provide Extensive support of Java Generics.
- To allow custom representations for objects
- To provide support for arbitrarily complex objects (with deep inheritance hierarchies and extensive use of generic types)
Installation of Gson
Gson targets Java based projects including android. That means we have at leats several ways of installing it depending on our build system.
(a) Gradle
For example if you are using android then most likely you are using android studio and gradle.
In that case you add the following in you app level build.gradle's dependencies:
(b) Maven
If you are creating a general java project then most likely you will use Maven:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
(c) Jar
The last option it to use jar directly. You download them from Maven Central and add to your project.
Download Jar here.
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:
JsonObject
JsonArray
JsonPrimitive
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:
- 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()
. - 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().
- 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.
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.
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.
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);
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);
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);
}
}
More Examples
Here are more examples
GSON - How to Parse Local JSON File
This is an android example of how to parse JSON file in GSON.
Gson is a Java library that can be used to convert Java Objects into their JSON representation.
Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of. There are a few open-source projects that can convert Java objects to JSON.
However, most of them require that you place Java annotations in your classes; something that you can not do if you do not have access to the source-code. Most also do not fully support the use of Java Generics. This library considers both of these as very important design goals.
In this lesson you will learn how to parse a local JSON file using GSON. GSON is the most popular JSON parsing library. You can use it to parse all sorts of JSON data in android and java in general. In this particular we wanna show you how to specifically parse local JSON data. By local we mean data stored under the raw
folder inside the res
directory.
Step 1: Install Gson
The first step is to install GSON. As popular as it is, GSON is a third party library. It was originally created by Google. It's been around for almost a decade so you can trust even in a production app.
Simply declare it in your app/build.gradle
and sync.
Use the following implementation statement to install it. You can use a later version.
Step 2: Add JSON file
The second step is to add some JSON data to the raw
directory. In your res
directory create a raw
folder and inside it add the shown JSON file. What you are seeing is a JSON object. It has three properties: a module name, a teacher and a semester. The Teacher itself is a JSON object. The module name is a string, while the semester is an integer.
/raw/course.json
{
"module_name": "Mobile Application Development",
"teacher": {
"first_name": "Nguyên",
"last_name": "Baylatry"
},
"semester": 8
}
Step 3: Design Layout
Next design your main layout with a bunch of TextViews inside a RelativeLayout. The target layout is the activity_main xml
layout. These textviews will show the individual values of our JSON object. Our root element is the RelativeLayout. Then 2, 3 and 4 represent our TextViews. That's all we need to design our layout.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="fr.esilv.gsonexample.MainActivity">
<TextView
android:id="@+id/moduleNameTextView"
style="@style/TextAppearance.AppCompat.Large"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/teacherTextView"
style="@style/TextAppearance.AppCompat.Medium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/moduleNameTextView"/>
<TextView
android:id="@+id/semesterNameTextView"
style="@style/TextAppearance.AppCompat.Medium"
android:layout_width="wrap_content"
android:layout_below="@+id/teacherTextView"
android:layout_height="wrap_content"/>
</RelativeLayout>
Step 4: Create Models
Create two model class as shown below:
(a). Teacher.java
A Teacher class to represent a single teacher. Each teacher will have a first name and a last name. Take note of the SerializedName
annotations decorated on those properties and keys passed to them.
package fr.esilv.gsonexample.models;
import com.google.gson.annotations.SerializedName;
public class Teacher {
@SerializedName("first_name")
private String firstName;
@SerializedName("last_name")
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
(b). Course.java
We also have a course model class. It has the module name, teacher and semester as the properties. Only the module name in this case will be serialized. Our whole JSON object will be mapped to this particular class. You can see it also includes the Teacher object which too has properties serialized.
package fr.esilv.gsonexample.models;
import com.google.gson.annotations.SerializedName;
public class Course {
@SerializedName("module_name")
private String moduleName;
private Teacher teacher;
private int semester;
public String getModuleName() {
return moduleName;
}
public void setModuleName(String moduleName) {
this.moduleName = moduleName;
}
public Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
public int getSemester() {
return semester;
}
public void setSemester(int semester) {
this.semester = semester;
}
}
Step 5: Load JSON
Our last step will be to load our JSON. We do this inside of our MainActivity
. Proceed to the class, add imports. Then extend the AppCompatActivity. As instance fields, declare our TextViews
.
Then inside the onCreate
method, reference them. To load our JSON data, invoke the initialize data function. In that function we load our JSON data, by first invoking openRawResources
method. Inside the method we pass the ID of the JSON file.
This function will return an InputStream. We then instantiate a ByteArrayOutputStream
. We will be writing the data we are reading from InputStream into this ByteArrayOutputStream
. We do this, inside a try-catch block, so that we catch any IO Exception
. We then convert the ByteArrayOutputStream
object into a string, using the toString
method.
Then by invoking the from JSON
method, and passing the ByteArrayOutputStream
object, we will get a Course object. That's how load a JSON file from the raw folder using Google JSON library.
MainActivity.java
package fr.esilv.gsonexample;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import com.google.gson.Gson;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import fr.esilv.gsonexample.models.Course;
import fr.esilv.gsonexample.models.Teacher;
public class MainActivity extends AppCompatActivity {
private TextView moduleNameTextView;
private TextView teacherTextView;
private TextView semesterNameTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
moduleNameTextView = (TextView) findViewById(R.id.moduleNameTextView);
teacherTextView = (TextView) findViewById(R.id.teacherTextView);
semesterNameTextView = (TextView) findViewById(R.id.semesterNameTextView);
initializeData();
}
private void initializeData() {
//get the raw Json as A Stream
InputStream courseAsInputStream = getResources().openRawResource(R.raw.course);
//get a String from the Stream
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try {
i = courseAsInputStream.read();
while (i != -1) {
byteArrayOutputStream.write(i);
i = courseAsInputStream.read();
}
courseAsInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
String courseAsString = byteArrayOutputStream.toString();
//parse the String as an Object using Gson
Gson gson = new Gson();
Course course = gson.fromJson(courseAsString, Course.class);
//populate the View
if (course != null) {
moduleNameTextView.setText(course.getModuleName());
Teacher teacher = course.getTeacher();
teacherTextView.setText(getString(R.string.teacher, teacher.getFirstName(), teacher.getLastName()));
semesterNameTextView.setText(getString(R.string.semester, course.getSemester()));
}
}
}