Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"

like image 754
geekyaleks Avatar asked Feb 13 '13 16:02

geekyaleks


3 Answers

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.

like image 50
Brian Roach Avatar answered Sep 28 '22 23:09

Brian Roach


my issue was bit different actually i was getting Null values for the properties of POJO class.

however i solved the problem by giving mapping to properties in my pojo class like this :

@JsonProperty("PROPERTY_NAME")

thought it may help someone :)

like image 25
Prateek S Avatar answered Sep 28 '22 22:09

Prateek S


The following solution saved me.

  objectMapper.setSerializationInclusion(Include.NON_NULL);
like image 35
Ghost Rider Avatar answered Sep 29 '22 00:09

Ghost Rider