Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon

How to Convert POJO to JSON Using Gson in Android Studio

Save for later
  • 6 min read
  • 01 Jul 2014

article-image

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
  2. Change the Application name to GsonTest. Click Next
  3. 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.gradle script 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 Files icon. 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 https://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

Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at $19.99/month. Cancel anytime


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.