Wednesday, 28 October 2015

Jackson: Convert JSON to object

Following statements are used to convert JSON to Java object.
ObjectMapper mapper = new ObjectMapper();
Employee emp1 = mapper.readValue(json, Employee.class);

Above statements convert the JSON string json to Employee object.

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.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {
  public static void main(String args[]) throws JsonGenerationException,
      JsonMappingException, 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();
    String json = mapper.writeValueAsString(emp);

    System.out.println(json);

    System.out.println("Deserializing JSON to Object");
    Employee emp1 = mapper.readValue(json, Employee.class);

    System.out.println(emp1.getId() + " " + emp1.getFirstName() + " "
        + emp1.getLastName() + " " + emp1.getHobbies());
  }
}


Output
{"id":1,"firstName":"Hari Krishna","lastName":"Gurram","hobbies":["Trekking","Blogging","Cooking"]}
Deserializing JSON to Object
1 Hari Krishna Gurram [Trekking, Blogging, Cooking]



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment