Parsing JSON data using Google GSON library in Eclipse

Setup:
1. Download gson library
2. Add as external jar from your eclipse project

JSON String:
{
“status”:”200″,
“error_message”:”Success”,
“item”:
[{“ID”:”18″, “Name”:”Name A”} ,
{“ID”:”19″, “Name”:”Name B”} ,
{“ID”:”20″, “Name”:”Name C”} ,
{“ID”:”21″, “Name”:”Name D”}]
}

Java class to implement the parsing

public class gsonexample {

	public gsonexample(){}

	public void parseJson(String url){
		try{
			Reader reader = new InputStreamReader(new URL("url").openStream()); //Read the json output
			Gson gson = new GsonBuilder().create();
			DataObject obj = gson.fromJson(reader, DataObject.class);
			System.out.println(obj);
		}catch(Exception e){
			System.out.println(e);
		}
	}

	private class DataObject{ //This class should match your json object structure
		private int status;
		private String error_message;
		private List<Item> item; // This is for the inner array
		@Override
	    public String toString() {
	        return status + " - " + error_message+ " (" + item + ")";
	    }
	}

	private class Item{ //This is the inner array class
		public int ID;
		public String Name;
		@Override
	    public String toString() {
	        return ID + " - " + Name +"\n";
	    }
	}
}

Posted on February 28, 2014, in Education and tagged , , , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: