geekyaleks geekyaleks - 1 year ago 152
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?


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("********************* 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("********************* 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 Source

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:

  // 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download