Site icon

Convert object to/from json string in java (jackson objectmapper-example)

Jackson ObjectMapper Maven Dependencies

<dependency>
	<groupId>com.fasterxml.jackson.core</groupId> 
	<artifactId>jackson-databind</artifactId>
	<version>2.7.1</version> 
</dependency>

Program – Convert object to/from json string in java

1.) Person Class:

The person class contains the data members as follows:

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:

We are performing couple of operations in JSONObjectConverter class:

  1. Convert Person Object (POJO) to JSON string
  2. Convert JSON string to Person object (POJO)
import java.io.IOException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public class JSONObjectConverter 
{
    public static void main( String[] args ) throws IOException
    {
    	ObjectMapper objectMapper = new ObjectMapper();
    	//Set pretty printing of json
    	objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    	Person objPerson = new Person("Mike", "harvey", 34, "001894536");
    	
    	//Convert Person object to json
    	String json = objectMapper.writeValueAsString(objPerson);
    	System.out.println("1. Convert Person object to Json");
    	System.out.println(json);
    	
    	//Convert to json to person object    	
    	System.out.println("2. Convert JSON to person object");
    	Person objFromJson = objectMapper.readValue(json, Person.class);
    	System.out.println(objFromJson); 
    }
}

Output – convert object to/from json string (objectmapper)

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

Download Example Code – Jackson Object to JSON

Exit mobile version