Wednesday, 28 October 2015

Jackson: Convert object to json using ObjectMapper

ObjectMapper class is used to convert Java object to JSON, and JSON to Java oject.
Step 1: Instantiate ObjectMapper class.
ObjectMapper mapper = new ObjectMapper();

Step 2: Call any write methods to convert Java object to JSON.
mapper.writeValue(System.out, emp);
Above statement write the JSON of emp to system console.

import java.util.ArrayList;
import java.util.List;

public class Employee {
	private int id;
	private String firstName;
	private String lastName;
	private List<String> hobbies = new ArrayList<>();

	public int getId() {
		return id;
	}

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

	public List<String> getHobbies() {
		return hobbies;
	}

	public void setHobbies(List<String> hobbies) {
		this.hobbies = hobbies;
	}

	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("Employee [id=").append(id).append(", firstName=")
				.append(firstName).append(", lastName=").append(lastName)
				.append(", hobbies=").append(hobbies).append("]");
		return builder.toString();
	}

}


import java.io.IOException;

import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {
	public static void main(String args[]) throws IOException {
		Employee emp = new Employee();

		emp.setFirstName("Hari Krishna");
		emp.setId(1);
		emp.setLastName("Gurram");

		emp.getHobbies().add("Trekking");
		emp.getHobbies().add("Blogging");
		emp.getHobbies().add("Cooking");

		ObjectMapper mapper = new ObjectMapper();
		mapper.writeValue(System.out, emp);
	}
}


Output

{"id":1,"firstName":"Hari Krishna","lastName":"Gurram","hobbies":["Trekking","Blogging","Cooking"]}




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment