Wednesday 28 October 2015

Jackson: Pretty print JSON

By enabling 'SerializationFeature.INDENT_OUTPUT' we can print pretty print JSON.

ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
String json = mapper.writeValueAsString(emp);

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;
import com.fasterxml.jackson.databind.SerializationFeature;

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();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    String json = mapper.writeValueAsString(emp);
    
    System.out.println(json);

  }
}


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



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment