Thursday 21 April 2016

Genson: Pretty json

You need to create Genson instance like below to get pretty json.

Genson prettyGenson = new GensonBuilder().useIndentation(true).create();
import com.owlike.genson.annotation.JsonIgnore;

public class Employee {
 private String id;
 private String firstName;
 private String lastName;
 @JsonIgnore
 private String password;

 public String getId() {
  return id;
 }

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

 @JsonIgnore
 public String getPassword() {
  return password;
 }

 @JsonIgnore
 public void setPassword(String password) {
  this.password = password;
 }

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

}

import java.util.List;
import java.util.Map;

import com.owlike.genson.GenericType;
import com.owlike.genson.Genson;
import com.owlike.genson.GensonBuilder;

public class JSONUtil {
 private static Genson genson = new Genson();
 private static Genson skipNullGenson = new GensonBuilder().setSkipNull(true).create();
 private static Genson prettyGenson = new GensonBuilder().useIndentation(
   true).create();

 public static String getJson(Object obj) {
  return genson.serialize(obj);
 }

 public static <T> T deserializeJson(String json, Class<T> clazz) {
  return genson.deserialize(json, clazz);
 }

 public static <T> List<T> getListOfObjects(String json,
   GenericType<List<T>> list) {
  return genson.deserialize(json, list);
 }

 public static <K, V> Map<K, V> getMap(String json,
   GenericType<Map<K, V>> map) {
  return genson.deserialize(json, map);
 }

 public static String getJsonSkipNulls(Object obj) {
  return skipNullGenson.serialize(obj);
 }
 
 public static String getPrettyJson(Object obj){
  return prettyGenson.serialize(obj);
 }
}

public class Test {

 public static void main(String args[]) {
  Employee emp1 = new Employee();

  emp1.setId("E432156");
  emp1.setFirstName("Hari krishna");
  emp1.setPassword("Password123");

  String json = JSONUtil.getPrettyJson(emp1);

  System.out.println(json);
 }
}


Output
{
  "firstName":"Hari krishna",
  "id":"E432156",
  "lastName":null
}



Previous                                                 Next                                                 Home

No comments:

Post a Comment