Jackson JSON Generator Generates Null JSON Values ​​for Missing Objects

I started using Jackson as a JSON generator as an alternative to google GSON. I ran into a problem when Jackson generates an object: null if the object is really zero. GSON, on the other hand, generates a NO entry in JSON, which is the behavior I want. Is there a way to stop Jackson from creating a null object / value when the object is missing?

Jackson

ObjectMapper mapper = new ObjectMapper(); StringWriter sw = new StringWriter(); mapper.writeValue(sw, some_complex_object); String jackson = sw.getBuffer().toString(); System.out.println("********************* START JACKSON JSON ****************************"); System.out.println(jackson); System.out.println("********************* END JACKSON JSON ****************************"); 

generates this:

{"eatwithrustyspoon": { "urlList": null , "device": "iPad", "os": "iPhone OS", "peer_id":

and GSON is as follows:

  Gson gson = new Gson(); String json = gson.toJson(some_complex_object); System.out.println("********************* START GSON JSON ****************************"); System.out.println(json); System.out.println("********************* END GSON JSON ****************************"); 

and it generates this (this is what I want - note that "urlList": null was not generated):

{"eatwithrustyspoon": {"device": "iPad", "os": "iPhone OS", "peer_id"

+8
java json jackson gson
source share
3 answers

From Jackson's FAQ :

Is it possible to omit Bean properties with a null value? ("how to prevent writing null properties", "how to suppress null values")

Yes. By JacksonAnnotationSerializeNulls you can use:

  objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); // or (for older versions): objectMapper.configure(SerializationConfig.WRITE_NULL_PROPERTIES, false); 

and voila, no more than zero values. Note that you MUST configure mapper to beans, serialize, as this parameter can be cached along with serializers. Therefore, installation too late may prevent the changes from taking effect.

+12
source share

The following solution saved me.

  objectMapper.setSerializationInclusion(Include.NON_NULL); 
+1
source share

my problem was a bit different, I was getting Null values ​​for the properties of the POJO class.

however, I solved the problem by setting property mapping in my pojo class as follows:

@JsonProperty ("PROPERTY_NAME")

thought it could help someone :)

+1
source share

All Articles