Search code examples
javajacksonjackson-databind

Jackson Serialize: Include empty string if any


I am trying to serialize a class into JSON string with jackson.

Class

public class Response {


  @JsonProperty("status")
  private Short status;

  @JsonProperty("data")
  @JsonRawValue
  private String data;

  @JsonProperty("message")
  @JsonRawValue
  private String message;
  
}

Using the following code to serialize

JsonFactory jsonFactory = new JsonFactory();
jsonFactory.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET,false);
ObjectMapper mapper;
mapper = new ObjectMapper(jsonFactory);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.findAndRegisterModules();

Response responseInstance = new Response();
responseInstance.setStatus((short) 400);
responseInstance.setMessage("");
System.out.println(mapper.writeValueAsString(responseInstance));

I am getting the following value while serialization when value of message is "".

{
   "status": 400,
   "message":
}

Instead of

{
   "status": 400,
   "message":""
}

When the value is null, it is skipped from serialization which is expected. But when the value is "", i want that value be part of the serialization. How do i inlcude "" in the value while serialization?


Solution

  • @JsonRawValue is the "problem".

    Marker annotation that indicates that the annotated method or field should be serialized by including literal String value of the property as is, without quoting of characters.

    […]

    Warning: the resulting JSON stream may be invalid depending on your input value.

    In other words: everything works as expected. Your code tells the serializer to not add the quotes. And the serializer follows suit and doesn't add them.

    If you need regular strings in JSON, then do not configure your serializer to remove them.