Close
Glad You're Ready. Let's Get Started!

Let us know how we can contact you.

Thank you!

We'll respond shortly.

LABS
Even Better Parsing of JSON Data on Android

Last spring I wrote a post about how to parse JSON data efficiently on Android using Google GSON’s JsonReader class. I’m happy to report that I’ve found an even easier way to do the same thing! Google’s GSON is a marvellous thing.

Let’s say you have some JSON data. This file shows a simple list of restaurants and their opening hours:

{
    "items": [
        {
            "id": "A19",
            "name": "Extra Beans",
            "addr": "15 Main St",
            "hours": {
                "monday": "closed",
                "tuesday": "9 AM to 5 PM",
                "wednesday": "9 AM to 6 PM",
                "thursday": "9 AM to 8 PM",
                "friday": "8 AM to 8 PM",
                "saturday": "noon to 5 PM",
                "sunday": "closed"
            }
        },
        {
            "id": "B24",
            "name": "Tamales Adventure",
            "addr": "54 Queen St",
            "hours": {
                "monday": "closed",
                "tuesday": "9 AM to 5 PM",
                "wednesday": "9 AM to 6 PM",
                "thursday": "9 AM to 8 PM",
                "friday": "8 AM to 8 PM",
                "saturday": "noon to 5 PM",
                "sunday": "closed"
            }
        },
        {
            "id": "C73",
            "name": "Soup Explosion",
            "addr": "99 King St",
            "hours": {
                "monday": "closed",
                "tuesday": "9 AM to 5 PM",
                "wednesday": "9 AM to 6 PM",
                "thursday": "9 AM to 8 PM",
                "friday": "8 AM to 8 PM",
                "saturday": "noon to 5 PM",
                "sunday": "closed"
            }
        },
        {
            "id": "E87",
            "name": "Candy Party",
            "addr": "654 Eastern Ave",
            "hours": {
                "monday": "closed",
                "tuesday": "9 AM to 5 PM",
                "wednesday": "9 AM to 6 PM",
                "thursday": "9 AM to 8 PM",
                "friday": "8 AM to 8 PM",
                "saturday": "noon to 5 PM",
                "sunday": "closed"
            }
        }
    ]
}

In my previous blog post, I constructed my models with elaborate createFromJson methods that parsed the JSON data intimately as a stream. I’ve learned that this strategy is overkill. You can construct your models using the SerializedName annotation on your fields. GSON will fill in the rest for you automatically.

I can parse the above JSON into three models, an ItemList, an Item, and an Hours object:

package com.xtremelabs.gsonexample.model;

import java.io.Serializable;
import java.util.List;

import com.google.gson.annotations.SerializedName;

public class ItemList implements Serializable {

	private static final long serialVersionUID = -3676104445260928528L;

	public static final String DEFAULT_FILENAME = "items.json";

	@SerializedName( "items" )
	private final List<Item> _items;

	public ItemList( final List<Item> items ) {
		_items = items;
	}

	public ItemList( final ItemList itemListToCopy ) {
		_items = itemListToCopy.getItems();
	}

	public List<Item> getItems() {
		return _items;
	}

}

 

package com.xtremelabs.gsonexample.model;

import java.io.Serializable;

import com.google.gson.annotations.SerializedName;

public class Item implements Serializable {

	private static final long serialVersionUID = -3398208377833320923L;

	@SerializedName("name")
	private final String _name;

	@SerializedName("addr")
	private final String _address;

	@SerializedName("id")
	private final String _id;

	@SerializedName("hours")
	private final Hours _hours;

	public Item(String name, String address, String id, Hours hours) {
		_name = name;
		_address = address;
		_id = id;
		_hours = hours;
	}

	public Item(final Item cafeListToCopy) {
		_name = cafeListToCopy.getName();
		_address = cafeListToCopy.getAddress();
		_id = cafeListToCopy.getId();
		_hours = cafeListToCopy.getHours();
	}

	public String getName() {
		return _name;
	}

	public String getAddress() {
		return _address;
	}

	public String getId() {
		return _id;
	}

	public Hours getHours() {
		return _hours;
	}

	@Override
	public String toString() {
		return getName();
	}

}

 

package com.xtremelabs.gsonexample.model;

import java.io.Serializable;

import com.google.gson.annotations.SerializedName;

public class Hours implements Serializable {

	@SerializedName("monday")
	private final String _monday;

	@SerializedName("tuesday")
	private final String _tuesday;

	@SerializedName("wednesday")
	private final String _wednesday;

	@SerializedName("thursday")
	private final String _thursday;

	@SerializedName("friday")
	private final String _friday;

	@SerializedName("saturday")
	private final String _saturday;

	@SerializedName("sunday")
	private final String _sunday;

	public Hours(String monday, String tuesday, String wednesday, String thursday, String friday, String saturday, String sunday) {
		_monday = monday;
		_tuesday = tuesday;
		_wednesday = wednesday;
		_thursday = thursday;
		_friday = friday;
		_saturday = saturday;
		_sunday = sunday;
	}

	public Hours(final Hours hoursToCopy) {
		_monday = hoursToCopy.getMonday();
		_tuesday = hoursToCopy.getTuesday();
		_wednesday = hoursToCopy.getWednesday();
		_thursday = hoursToCopy.getThursday();
		_friday = hoursToCopy.getFriday();
		_saturday = hoursToCopy.getSaturday();
		_sunday = hoursToCopy.getSunday();
	}

	public String getMonday() {
		return _monday;
	}

	public String getTuesday() {
		return _tuesday;
	}

	public String getWednesday() {
		return _wednesday;
	}

	public String getThursday() {
		return _thursday;
	}

	public String getFriday() {
		return _friday;
	}

	public String getSaturday() {
		return _saturday;
	}

	public String getSunday() {
		return _sunday;
	}
}

Reading this JSON is dirt-simple now. Once I get my hands on an input stream with the JSON data, I only need a few lines of code to load the objects. It even knows how to load the Hours object. I didn’t have to do anything.

	final InputStreamReader reader = new InputStreamReader(inputStream);
	final Gson gson = new Gson();
	final ItemList itemList = gson.fromJson(reader, ItemList.class);

You can find a complete project that demonstrates this example by cloning this public repository I’ve put together:

git clone git@github.com:xtreme-rob-szumlakowski/gson-example.git

Although I have framed this post as an Android solution, it is not Android-specific. You can use Google GSON in any Java project.

Comments