Monday 24 November 2014

Jackson Ignore null / empty values in JSON serialization with @JsonInclude

Hi Guys,

In this post we are going to see how to ignore null and Empty values using Jackson @Include Annotations.
Jackson 2.x provides @JsonInclude annotation to specify the property that should be included during serialization based on its values.

@JsonInclude can have following values
  • Include.ALWAYS indicates that property is serialized irrespective of its value
  • Include.NON_DEFAULT indicates that property is serialized if its value is different from default settings
  • Include.NON_EMPTY indicates that property is serialized if its value is not null and not empty
  • Include.NON_NULL indicates that property is serialized if its value is not null
Jackson 2.x JAR Dependency

To serialize or unserialize JSON using Jackson 2.x requires following three jar files in classpath
  • Core – jackson-core-2.2.3.jar
  • Annotations – jackson-annotations-2.2.3.jar
  • Databind – jackson-databind-2.2.3.jar
Jackson 2.x JAR Download URL
Download Jackson 2.x Libraries

Jackson Ignore null/empty values Example
User.java
In User Java Bean class, city is annotated with @JsonInclude(value=Include.NON_EMPTY) so it will be included in serialization only if its value is non null and non empty string. Similarly, height is annotated with @JsonInclude(value=Include.NON_NULL) so it will included in serialization only if its value is non null.


package in.binding
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
/**
* @author Visakh
*/
public class User {

private String name;
@JsonInclude(value=Include.NON_EMPTY)
private String city;
private Integer age;
@JsonInclude(value=Include.NON_NULL)
private Double height;
private Boolean married;

public User() {
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}

public Double getHeight() {
return height;
}

public void setHeight(Double height) {
this.height = height;
}

public Boolean getMarried() {
return married;
}

public void setMarried(Boolean married) {
this.married = married;
}

@Override
public String toString() {
return "User [name=" + name + ", city=" + city + ", age=" + age
+ ", height=" + height + ", married=" + married + "]";
}
}

JsonSerializationExample.java

In JsonSerializationExample, city is set to empty string and height is not set i.e. eventually set to null.

package in.binding;

import java.io.IOException;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
* @author Visakh
*/
public class JsonSerializationExample {

public static void main(String args[]) {

User user = new User();
user.setName("Visakh");
user.setCity(""); //city is set to empty string
user.setAge(23);
// user.setHeight(5.7); height is not set; hence it will be null
user.setMarried(Boolean.FALSE);
System.out.println("User: " + user);

try {
// ObjectMapper provides functionality for data binding between
// Java Bean Objects/POJO and JSON constructs/string
ObjectMapper mapper = new ObjectMapper();

// serialize userList to JSON format and write to file
String jsonString = mapper.writeValueAsString(user);

System.out.println("JSON string: " + jsonString);
} catch (IOException e) {
e.printStackTrace();
}
}
}

Example Output
As shown in log output, city and height are not serialized to JSON string.


  • User: User [name=Visakh, city=, age=23, height=null, married=false]
  • JSON string: {"name":"Visakh","age":23,"married":false}

If you want to ignore null or empty values globally you can set it using Mapper Serialization.
Instead of using @Include in all classes use Serialization in Main class.

  • mapper.setSerializationInclusion(Include.NON_EMPTY);
By using setSerializationInclusion Method you can set it globally.

That's All Folks


Saturday 8 November 2014

Jackson Streaming API to Read JSON

Hi guys
In the previous post we saw how to write JSON using Jackson. Lets see how to read JSON using Jackson Streaming API.

  1. JsonParser – Parse JSON.

JsonParser



On the other hand, use JsonParser to parse or read above file “data.json“, and display each of the values.

import java.io.File;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.JsonMappingException;

public class Read {
public static void main(String[] args) {

try {

JsonFactory jfactory = new JsonFactory();

/*** read from file ***/
JsonParser jParser = jfactory.createJsonParser(new File("./src/data.json"));

// loop until token equal to "}"
while (jParser.nextToken() != JsonToken.END_OBJECT) {

String fieldname = jParser.getCurrentName();
if ("blogname".equals(fieldname)) {

// current token is "blogname",
// move to next, which is "name"'s value
jParser.nextToken();
System.out.println(jParser.getText()); // display oraclejavatechzone.com

}

if ("subject".equals(fieldname)) {

// current token is "subject",
// move to next, which is "name"'s value
jParser.nextToken();
System.out.println(jParser.getText()); // display java

}

if ("year".equals(fieldname)) {

// current token is "year",
// move to next, which is "name"'s value
jParser.nextToken();
System.out.println(jParser.getIntValue()); // display 2013

}

if ("posts".equals(fieldname)) {

jParser.nextToken(); // current token is "[", move next

// posts is array, loop until token equal to "]"
while (jParser.nextToken() != JsonToken.END_ARRAY) {

// display post11, post2, post3
System.out.println(jParser.getText());

}

}

}
jParser.close();

} catch (JsonGenerationException e) {

e.printStackTrace();

} catch (JsonMappingException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}
}
}

Output:
That's All guys..




Jackson Streaming API to Write JSON

Hi guys,
In this post i show you how to create JSON file using Jackson Streaming API.

Jackson supports read and write JSON via high-performance Jackson Streaming APIs, or incremental mode. Read this Jackson Streaming APIs document for detail explanation on the benefit of using streaming API.

Jackson’s streaming processing is high-performance, fast and convenient, but it’s also difficult to use, because you need to handle each and every detail of JSON data.

In this tutorial, i show you how to use following Jackson streaming APIs to read and write JSON data.
  1. JsonGenerator – Write to JSON.
  2. JsonParser – Parse JSON.
JsonGenerator
In this example, you use “JsonGenerator” to write JSON “field name”, “values” and “array of values” into a file name “file.json“. See code comments for self-explanatory.


import java.io.File;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonGenerator;

public class WriteJson {
public static void main(String[] args) {

try {

JsonFactory jfactory = new JsonFactory();

/*** Write JSON TO FILE ***/
JsonGenerator jGenerator = jfactory.createGenerator(new File("./src/data.json"), JsonEncoding.UTF8);
jGenerator.writeStartObject();  //{

jGenerator.writeStringField("blogname", "oraclejavatechzone.com");
jGenerator.writeStringField("subject", "java");

jGenerator.writeNumberField("year", 2013);

jGenerator.writeFieldName("posts"); //"posts":

jGenerator.writeStartArray(); //[
jGenerator.writeString("post 1");
jGenerator.writeString("post 2");
jGenerator.writeString("post 3");

jGenerator.writeEndArray(); \\]
jGenerator.writeEndObject(); //}

jGenerator.close();
System.out.println("File write successfully");

} catch (JsonGenerationException e) {
e.printStackTrace();

} catch (IOException e) {
e.printStackTrace();

}
}
}

As result, following new file named “data.json” is created :


That's All Folks...