Converts Java Beans to JSON with GSON

Problem Statement: In Unit Testing we want to see the object content.

Solution: Use GSON and print the java beans info in JSON format.
Other way round is we used to spend lot of time in Writing reflection or over writing toString() of bean.
It is very difficult when we have complex data types and that part of code is keep changing.

<!-- This converts Java Beans to JSON -->
<dependency>
	<groupId>com.google.code.gson</groupId>
	<artifactId>gson</artifactId>
	<version>2.2.2</version>
</dependency>

import com.google.gson.Gson;

public class GSONTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		Student s1 = new Student();
		s1.setId(1);
		s1.setFirstName("Bhavani");
		s1.setLastName("Polimetla");

		Gson gson = new Gson();
		String json = gson.toJson(s1);
		System.out.println(json);

	}

	public static class Student {
		long id;
		String firstName;
		String lastName;

		public long getId() {
			return id;
		}

		public void setId(long id) {
			this.id = id;
		}

		public String getFirstName() {
			return firstName;
		}

		public void setFirstName(String firstName) {
			this.firstName = firstName;
		}

		public String getLastName() {
			return lastName;
		}

		public void setLastName(String lastName) {
			this.lastName = lastName;
		}
	}

}

Result:
{“id”:1,”firstName”:”Bhavani”,”lastName”:”Polimetla”}

Reference: https://sites.google.com/site/gson/Home

-o-

Advertisements

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