Web Development

Use Gson to work with JSON in your Android apps

In this Android tutorial, William J. Francis uses Gson to build up a standard Java entity and flatten it into JSON.

I know... Gson, JSON -- it sounds like a bad tongue twister. But if you've been involved in mobile apps that communicate with a server you've no doubt had a run-in with JSON. For the sake of any readers who aren't familiar with JavaScript Object Notation, Wikipedia defines JSON as follows:

"JSON, or JavaScript Object Notation is a lightweight text-based open standard designed for human-readable data interchange. It is derived from the JavaScript scripting language for representing simple data structures and associative arrays, called objects. Despite its relationship to JavaScript, it is language-independent, with parsers available for many languages."

I find myself converting objects to JSON and back again on a regular basis. If it's a tiny project, it's easy enough to override the to string method of an entity and do the conversion by hand. However, anything more complex than a couple of fixed objects, and you'll want a library to handle the conversions for you.

There are a number of JSON libraries available for Java and specifically Android. I've used the json.org library, Jackson, and Google GSON. Recently I've seen some blog posts touting the superior speed of Jackson over Gson. I admit the numbers are impressive, but more times than not, mobile apps aren't parsing huge JSON documents. Keeping that fact in mind, for my money Gson is far easier to use.

The following tutorial goes through the process of building up a standard Java entity and then flattening it into JSON. You can follow along with the tutorial below or download and import the entire project.

1. Create a new Android project in Eclipse. Target Android 1.6 or greater. Be sure to rename the startup activity Main.java.

2. The next step is to download the Gson jar file.

3. Create a new folder at the project level call libs (Figure A). Cut and paste the jar you downloaded into this directory. Figure A

4. Right-click the project's top most folder and select PROPERTIES | JAVA BUILD PATH and select the LIBRARIES tab.

5. Click the Add JARs button and select the Gson jar we added to the /libs folder (Figure B). Click OK. Figure B

6. Now we should have everything we need in place to start Gson'ing JSON. In the /res/layouts folder, add an edit text widget to the generated xml.

main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:gravity="center"
android:padding="16dip" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="GSON Example" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:minLines="4"
android:maxLines="4"
android:id="@+id/edit"/>
</LinearLayout>

7. Create a new class in the /src folder called MyEntity.java; this will be your standard Java entity with one exception. Notice the @ annotations? This is how Gson gives us control over how an object gets serialized. We include a property by adding the @Expose tag, and similarly we exclude a field by not annotating it. Gson also lets us change the flat name of a property using the @SerializedName annotation. In my opinion the annotation mechanism is straightforward and flexible.

MyEntity.java
package com.authorwjf.gsonex;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class MyEntity {
@Expose
private String name = null;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
//don't expose
private String race = null;
public String getRace() {
return race;
}
public void setRace(String race) {
this.race = race;
}
//change
@Expose
@SerializedName("gender")
private String sex = null;
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}

8. Once we've annotated the entity, all that is left is to create an instance of the Gson parser and call one of its methods. Let's look at our /src/Main.java file. We do everything in our on create override. The majority of the code is just instantiating an instance of our entity and populating the fields.

Main.java
package com.authorwjf.gsonex;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
public class Main extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MyEntity example = new MyEntity();
example.setName("Mr. Spock");
example.setRace("Vulcan");
example.setSex("male");
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
String flat = gson.toJson(example);
((EditText)findViewById(R.id.edit)).setText(flat);
}
}
Running the code in the emulator produces well formed javascript object notation. You see the output excluded the field we did not expose and changed the label of our "sex" field to "gender" (Figure C). Figure C

If you scroll back through the tutorial, you'll see there were more steps involved in downloading and importing the Gson libraries than actual coding. I'm a big fan of the KISS (Keep It Simple Stupid) principle of programming. In my experience, coding with Gson does exactly that.

What libraries do you use for handling JSON in your Android apps? If you use one I didn't mention, or have some additional insight on JSON parsing, sound off in the discussion thread.

About

William J Francis began programming computers at age eleven. Specializing in embedded and mobile platforms, he has more than 20 years of professional software engineering under his belt, including a four year stint in the US Army's Military Intellige...

0 comments