geekyaleks geekyaleks - 4 months ago 16
JSON Question

Jackson JSON generator creates null JSON values for missing objects

I've started using Jackson as a JSON generator, as an alternative to google GSON. I've run into an issue where Jackson is generating object: null if the object is indeed null. GSON on the other hand generates NO entry in JSON, which is the behavior I want. Is there a way to stop Jackson from generating null object/value when an 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 looks like this:

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 (which is what I want - note that "urlList":null was not generated) :

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

Answer

From the Jackson FAQ:

Can I omit writing of Bean properties with null value? ("how to prevent writing of null properties", "how to suppress null values")

Yes. As per 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 null values. Note that you MUST configure mapper before beans are serialized, since this setting may be cached along with serializers. So setting it too late might prevent change from taking effect.