How to configure fasterxml's objectMapper to handle empty string "" correctly

25 views Asked by At

I'm using fasterxml's ObjectMapper to serialize a java object and I'm having a problem with one of the fields.

Survey.java

public class Survey {

  private String id;
  private String answers;

  //getter and setter
}

This is the serialization code:

ObjectMapper om = new ObjectMapper();                   
ObjectWriter ow = om.writer().withDefaultPrettyPrinter();           
String json = ow.writeValueAsString(taskScheme.getSurvey());

the problem is that "answers" contains multiple values, and the serialization process escapes all the double quotes, like so:

"answers" : {"question3":["Item4"]} -> "answers" : "{\"question3\":[\"Item4\"]}"

In order to avoid this situation, I added the annotation @JsonRawValue to the "answers" field. It solved my problem but created a new one, because now whenever "answers" contains an empty string, the resulting serialization becomes:

"answers" : "" -> "answers" :

which is not even a valid JSON output...

How do I fix this problem?

Thanks in advance.

0

There are 0 answers