How an optional property can be ignored when using jackson to transform a Java object

I am using Jackson 1.9.2 (org.codehaus.jackson) to combine the Java object according to the JSON construct. Here is my java object:

Class ColorLight { String type; boolean isOn; String value; public String getType(){ return type; } public setType(String type) { this.type = type; } public boolean getIsOn(){ return isOn; } public setIsOn(boolean isOn) { this.isOn = isOn; } public String getValue(){ return value; } public setValue(String value) { this.value = value; } } 

If I did the following conversion, I would get the result that I want.

 ColorLight light = new ColorLight(); light.setType("red"); light.setIsOn("true"); light.setValue("255"); objectMapper mapper = new ObjectMapper(); jsonString = mapper.writeValueAsString(); 

jsonString will look like this:

 {"type":"red","isOn":"true", "value":"255"} 

But sometimes I don’t have the value of the isOn property

 ColorLight light = new ColorLight(); light.setType("red"); light.setValue("255"); 

But jsonString still looks like this:

 {"type":"red","isOn":"false", "value":"255"} 

Where "isOn: false" is the default for the Java Boolean type, which I do not want it to be there. How to remove isOn property in final json construct?

 {"type":"red","value":"255"} 
+6
source share
2 answers

If you want to skip the value if it is missing, you need to use the Boolean wrapper class instead of the primitive, which always has the value either true or false , and you need to tell Jackson not to serialize the zeros using @JsonInclude(Include.NON_NULL) .

+6
source

You can mark your class with @JsonSerialize(include = JsonSerialize.Inclusion.NON_DEFAULT) in the 1.x annotation, which indicates that only properties that have values ​​that differ from the default values ​​(the values ​​that they have when building the Bean with its constructor without arguments), to be included.

The @JsonInclude(JsonInclude.Include.NON_DEFAULT) used for version 2.x.

Here is an example:

 public class JacksonInclusion { @JsonSerialize(include = JsonSerialize.Inclusion.NON_DEFAULT) public static class ColorLight { public String type; public boolean isOn; public ColorLight() { } public ColorLight(String type, boolean isOn) { this.type = type; this.isOn = isOn; } } public static void main(String[] args) throws IOException { ColorLight light = new ColorLight("value", false); ObjectMapper mapper = new ObjectMapper(); System.out.println(mapper.writeValueAsString(light)); } } 

Output:

 {"type":"value"} 
+5
source

Source: https://habr.com/ru/post/971893/


All Articles