How to Convert POJO to JSON Using Gson in Android Studio

Troy Miles

July 01st, 2014

JSON has become the defacto standard of data exchange on the web. Compared to its cousin XML, it is smaller in size and faster to both create and parse. In fact, it seems so simple that many developers roll their own code to convert plain old Java objects or POJO to and from JSON. For simple objects, it is fairly easy to write the conversion code, but as your objects grow more complex, your code's complexity grows as well. Do you really want to maintain a bunch of code whose functionality is not truly intrinsic to your app?

Luckily there is no reason for you to do so. There are quite a few alternatives to writing your own Java JSON serializer/deserializer; in fact, json.org lists 25 of them. One of them, Gson, was created by Google for use on internal projects and later was open sourced. Gson is hosted on Google Code and the source code is available in an SVN repo.

Create an Android app

The process of converting POJO to JSON is called serialization. The reversed process is deserialization. A big reason that GSON is such a popular library is how simple it makes both processes. For both, the only thing you need is the Gson class. Let's create a simple Android app and see how simple Gson is to use.

1. Start Android Studio and select new project

Change the Application name to GsonTest. Click Next.

Click Next again.

4. Click Finish.

At this point we have a complete Android hello world app. In past Android IDEs, we would add the Gson library at this point, but we don't do that anymore. Instead we add a Gson dependency to our build.gradlescript and that will take care of everything else for us. It is super important to edit the correct Gradle file. There is one at the root directory but the one we want is at the app directory. Double-click it to open.

Locate the dependencies section near the bottom of the script. After the last entry add the following line:

compile 'com.google.code.gson:gson:2.2.4'

After you add it, save the script and then click the Sync Project with Gradle Filesicon. It is the fifth icon from the right-hand side in the toolbar. At this point, the Gson library is visible to your app. So let's build some test code.

Create test code with JSON

For our test we are going to use the JSON Test web service at http://www.jsontest.com/. It is a testing platform for JSON. Basically it gives us a place to send data to in order to test if we are properly serializing and deserializing data. JSON Test has a lot of services but we will use the validate service. You pass it a JSON string URL encoded as a query string and it will reply with a JSON object that indicates whether or not the JSON was encoded correctly, as well as some statistical information.

The first thing we need to do is create two classes. The first class, TestPojo, is the Java class that we are going to serialize and send to JSON Test. TestPojo doesn't do anything important. It is just for our test; however, it contains several different types of objects: ints, strings, and arrays of ints. Classes that you create can easily be much more complicated, but don't worry, Gson can handle it, for example:

1 package com.tekadept.gsontest.app;
2
3 public class TestPojo {
4 private intvalue1 = 1;
5 private String value2 = "abc";
6 private intvalues[] = {1, 2, 3, 4};
7 private transient intvalue3 = 3;
8
9 // no argsctor
10 TestPojo() {
11 }
12 }
13

Gson will also respect the Java transient modifier, which specifies that a field should not be serialized. Any field with it will not appear in the JSON.

The second class, JsonValidate, will hold the results of our call to JSON Test. In order to make it easy to parse, I've kept the field names exactly the same as those returned by the service, except for one. Gson has an annotation, @SerializedName, if you place it before a field name, you can have name the class version of a field be different than the JSON name. For example, if we wanted to name the validate field isValid all we would have to do is:

1 package com.tekadept.gsontest.app;
2
3 import com.google.gson.annotations.SerializedName;
4
5 public class JsonValidate {
6
7 public String object_or_array;
8 public booleanempty;
9 public long parse_time_nanoseconds;
10 @SerializedName("validate")
11 public booleanisValid;
12 public intsize;
13 }

By using the @SerializedName annotation, our name for the JSON validate becomes isValid. Just remember that you only need to use the annotation when you change the field's name.

In order to call JSON Test's validate service, we follow the best practice of not doing it on the UI thread by using an async task. An async task has four steps: onPreExecute, doInBackground, onProgressUpdate, and onPostExecute. The doInBackground method happens on another thread. It allows us to wait for the JSON Test service to respond to us without triggering the dreaded application not responding error. You can see this in action in the following code:

60 @Override
61 protected String doInBackground(String... notUsed) {
62 TestPojotp = new TestPojo();
63 Gsongson = new Gson();
64 String result = null;
65
66 try {
67 String json = URLEncoder.encode(gson.toJson(tp), "UTF-8");
68 String url = String.format("%s%s", Constants.JsonTestUrl, json);
69 result = getStream(url);
70 } catch (Exception ex){
71 Log.v(Constants.LOG_TAG, "Error: " + ex.getMessage());
72 }
73 return result;
74 }

To encode our Java object, all we need to do is create an instance of the Gson class, then call its toJson method, passing an instance of the class we wish to serialize.

Deserialization is nearly as simple. In the onPostExecute method, we get the string of JSON from the web service. We then call the convertFromJson method that does the conversion. First it makes sure that it got a valid string, then it does the conversion by calling Gson'sfromJson method, passing the string and the name of its the class, as follows:

81 @Override
82 protected void onPostExecute(String result) {
83
84 // convert JSON string to a POJO
85 JsonValidatejv = convertFromJson(result);
86 if (jv != null) {
87 Log.v(Constants.LOG_TAG, "Conversion Succeed: " + result);
88 } else {
89 Log.v(Constants.LOG_TAG, "Conversion Failed");
90 }
91 }
92
93 private JsonValidateconvertFromJson(String result) {
94 JsonValidatejv = null;
95 if (result != null &&result.length() >0) {
96 try {
97 Gsongson = new Gson();
98 jv = gson.fromJson(result, JsonValidate.class);
99 } catch (Exception ex) {
100     Log.v(Constants.LOG_TAG, "Error: " + ex.getMessage());
101                 }
102             }
103             return jv;
104         }

Conclusion

 For most developers this is all you need to know. There is a complete guide to Gson at https://sites.google.com/site/gson/gson-user-guide. The complete source code for the test app is at https://github.com/Rockncoder/GsonTest.

Discover more Android tutorials and extra content on our Android page - find it here.


About the author

Troy Miles, also known as the Rockncoder, currently has fun writing full stack code with ASP.NET MVC or Node.js on the backend and web or mobile up front. He started coding over 30 years ago, cutting his teeth writing games for C64, Apple II, and IBM PCs. After burning out, he moved on to Windows system programming before catching Internet fever just before the dot net bubble burst. After realizing that mobile devices were the perfect window into backend data, he added mobile programming to his repertoire. He loves competing in hackathons and randomly posting interesting code nuggets on his blog: http://therockncoder.blogspot.com/.

Get the right mindset for JavaScript

Looking to start out learning one of the most popular programming languages in the world? What you need is the perfect platform for getting into development the right way. This insightful guide offers everything the aspiring JavaScript developer needs to start getting their feet wet in no time at all.