geekyaleks
geekyaleks

Reputation: 1291

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"

Upvotes: 8

Views: 15617

Answers (3)

Prateek S
Prateek S

Reputation: 81

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 :)

Upvotes: 2

Ghost Rider
Ghost Rider

Reputation: 161

The following solution saved me.

  objectMapper.setSerializationInclusion(Include.NON_NULL);

Upvotes: 1

Brian Roach
Brian Roach

Reputation: 76908

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.

Upvotes: 12

Related Questions