IdleSun's Weblog

January 12, 2010

Gson – Complex Java Object with enum and list to JSON

Filed under: Java,JSON — idlesun @ 6:08 pm

Google GSON is pretty powerful with serializing a complex java object to json in one shot. This example shows the serialization  of a complex object that has a enum type member and nested list of simple objects:

public class TestMain {
	static enum Gender {Male, Female, NotKnown}

	static class Entry {
		public String name = "";
		public String phone = "";
		public Gender gender = Gender.NotKnown;
		public int birthYear;

		Entry(String name, String phone, Gender gender,int birthYear) {
			this.name = name;
			this.phone = phone;
			this.gender = gender;
			this.birthYear = birthYear;
		}
	}
	static class Contacts {
		public String name = "";
		public List entries = new ArrayList();
		Contacts(String name) {
			this.name = name;
		}
	}

	public static void main(String[] args) {
		// build contacts object
		Contacts contacts = new Contacts("My Contacts");
		contacts.entries.add(new Entry("John Doe", "123-234-3456", Gender.Male, 66));
		contacts.entries.add(new Entry("Jane Doe", "234-345-4567", Gender.Female, 67));

		// convert the contacts object to JSON string
		Gson gson = new Gson();
		System.out.println(gson.toJson(contacts));
	}
}

Here is the output:

{ 
  "name":"My Contacts",
  "entries":[
    {"name":"John Doe","phone":"123-234-3456","gender":"Male","birthYear":66},
    {"name":"Jane Doe","phone":"234-345-4567","gender":"Female","birthYear":67}
  ]
}

Nice, huh? Of course, check Gson User Guide for more details.

Advertisements

2 Comments »

  1. Thanks, just what I needed!

    Comment by techniata — October 4, 2010 @ 1:35 pm | Reply

  2. I dugg some of you post as I cogitated they were very useful extremely helpful dekaageeackg

    Comment by Johng255 — July 24, 2014 @ 2:45 am | Reply


RSS feed for comments on this post. TrackBack URI

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: