<

Work with Json(jackson lib) in Java

One of the common uses case is to work with Json string. Simple use case is to convert a strong to POJO object, java collections or vice versa. Json jackson library is a common library for such use cases.

Add the Jackson dependency in pom.xml file

<repositories>
    <repository>
        <id>codehaus</id>
        <url>http://repository.codehaus.org/org/codehaus</url>
    </repository>
  </repositories>
  
  <dependencies>
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.9.12</version>
    </dependency>
  </dependencies>

Consider a HashMap object with some fields

Map m = new HashMap();
Map personMap = new HashMap<>();
Map personDetail = new HashMap();
personDetail.put("firstname", "Bob");
personDetail.put("lastname", "jackson");
personDetail.put("age", "12");
personDetail.put("city", "Berlin");         
personMap.put("person", personDetail);

Convert the map to Json

ObjectMapper mapper = new ObjectMapper(); // jackson library provides the method
String json = mapper.writeValueAsString(personMap);

Convert json to Map

ObjectMapper mapper = new ObjectMapper(); // jackson library provides the method
Map map = mapper.readValue(json, Map.class);

Convert json to Java POJO object. Lets say Person.class

public class Person {

  private String firstname;
  private String lastname;
  private int age;
  private String address;
  
  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 int getAge() {
    return age;
  }
  public void setAge(int age) {
    this.age = age;
  }
  public String getAddress() {
    return address;
  }
  public void setAddress(String address) {
    this.address = address;
  }
}
ObjectMapper mapper = new ObjectMapper(); // jackson library provides the method
Person person = mapper.readValue(json, Person.class);

Convert only few fields of Pojo class. Lets say while converting we don't want address field to be imported

// use following annotation before field declaration.
@JsonIgnoreProperties(ignoreUnknown=true)
private String address;