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 -->


public class GSONTest {

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

		Student s1 = new Student();

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


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

		public long getId() {
			return id;

		public void setId(long 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;






Leave a Reply

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

You are commenting using your 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