Tuesday, 25 December 2018

Jackson: Include only non-null values in json serialization

Below statement include only non null values in json serialization.
@JsonInclude(JsonInclude.Include.NON_NULL)

Example
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({ "firstName", "lastName", "hobbies", "id" })
public class Employee {

}

Find the below working application.

Employee.java
package com.sample.model;

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

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({ "firstName", "lastName", "hobbies", "id" })
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();
 }

}

App.java
package com.sample.app;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sample.model.Employee;

public class App {

 public static void main(String args[]) throws JsonGenerationException, JsonMappingException, IOException {
  Employee emp = new Employee();

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

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

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

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



Previous                                                 Next                                                 Home

No comments:

Post a Comment