Site icon

Convert/ Serialize Object /POJO to /from JSON String in java (Gson & example)

GSON Maven dependency:

<dependency>
	<groupId>com.google.code.gson</groupId>
	<artifactId>gson</artifactId>
	<version>2.5</version>
</dependency>

Program – convert Object to /from JSON String in java (GSON & example)

1.) Person Class:

package org.learn.gson;

public class Person {
	public String firstName;
	public String lastName;
	public int age;
	public String contact;

	public Person(String firstName, String lastName, int age, String contact) {
		this.firstName = firstName;
		this.lastName = lastName;
		this.age = age;
		this.contact = contact;
	}

	public String toString() {
		return "[" + firstName + " " + lastName + " " + age + " " + contact + "]";
	}
}

2) JSONObjectConverter Class:

JSONObjectConverter is responsible for performing following operations.

  1. Convert Person Object to JSON String.
    • Serialization of Object to JSON String.
  2. Convert JSON String to person object.
    • Deserialization of JSON String to Person Object.
package org.learn.gson;

import java.lang.reflect.Type;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

public class JSONObjectConverter {
	public static void main(String[] args) {
		Gson objGson = new GsonBuilder().setPrettyPrinting().create();
		Person objPerson = new Person("Mike", "harvey", 34, "001894536");
		// Convert Person object to json
		String json = objGson.toJson(objPerson);
		System.out.println("1. Convert Person object to Json");
		System.out.println(json);

		// Convert to json to person object
		Type listType = new TypeToken() {
		}.getType();
		System.out.println("2. Convert JSON to person object");
		Person objFromJson = objGson.fromJson(json, listType);
		System.out.println(objFromJson);
	}
}

Download – Serializae & Deserialize or convert object to/from JSON (GSON)

Output – convert object to/from JSON in java (GSON & example)

1. Convert Person object to Json
{
  "firstName": "Mike",
  "lastName": "harvey",
  "age": 34,
  "contact": "001894536"
}
2. Convert JSON to person object
[Mike harvey 34 001894536]
Exit mobile version