Dealing with Java and JSON conversion

When you are trying to convert any java object to json, you may run in to this problem.

“com.fasterxml.jackson.core.JsonGenerationException: Null key for a Map not allowed in JSON (use a converting NullKeySerializer?)”

This is due to null key in the map of objects (or collection of objects). JsonGenerator cannot serialize the null key into json.

Ignore ‘null’ values in the map:

So we can ignore ‘null’ key and values from the ObjectMapper by using:

ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);

Now any null value in Map object serialized through this mapper is going to be ignored.

Serialise a map with ‘null’ key:

By default, Jackson doesn’t allow the serialization of a Map with a null key. If you do try to write out such a map, you’ll get the following exception:

com.fasterxml.jackson.core.JsonGenerationException: Null key for a Map not allowed in JSON (use a converting NullKeySerializer?)

you can define a custom, null key serializer and override the default behavior:

class CustomNullKeySerializer extends StdSerializer {
public CustomNullKeySerializer () {
this(null);
} public CustomNullKeySerializer (Class t) {
super(t);
}

@Override
public void serialize(Object nullKey, JsonGenerator jsonGenerator, SerializerProvider unused)
throws IOException, JsonProcessingException {
jsonGenerator.writeFieldName("");
}
}

Now the Map with the null key will work just fine – and the null key will be written as an empty String.

Ignore ‘Null’ fields globally:

You can also set to ignore the null fields globally by

mapper.setSerializationInclusion(Include.NON_NULL);

Now any null field in any class serialized through this mapper is going to be ignored.

Leave a Reply

Your email address will not be published. Required fields are marked *