1

I want to convert empty string values from attribute and replace it with null in my API response model object.

Lets say the API response is Transaction which contains 2 instance variable of type TransDetails and UserDetails. These two model classes contains around 100 string attributes.

Now some of the attributes of TransDetails and UserDetails are showing empty string in API response.

How can I change it to null in jackson 2?

I tried this solutions, but its not working in class level.

J.F.
  • 13,927
  • 9
  • 27
  • 65
Ansar Samad
  • 572
  • 2
  • 11
  • 34
  • Could you please provide code for you controller and the object that you are returning. Because by default you would get the null for each field which does not have any value set during the period , unless you have used some "@JsonInclude(JsonInclude.Include.NON_NULL)" which will make only non null json to be dislayed . something like below. { "system": "mySystem", "created": null, "createdBy": null } – Ajeet Maurya Dec 02 '20 at 18:49

2 Answers2

0

I believe you may try to configure ObjectMapper smth. like below

final ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);

this might be useful jackson-databind

  • I tried this , but its not working in jackson 2 and latest spring boot APIs – Ansar Samad Dec 03 '20 at 12:49
  • According to my investigation the solution I advice you did not suppose to convert empty string to null, so that's why it does not work. Sorry for that. For now, I think either requiring a setter or custom deserializer, that does that will probably be the best option. Since behavior itself for ACCEPT_EMPTY_STRING_AS_NULL_OBJECT is intended. this is according to https://github.com/FasterXML/jackson-databind/issues/1563 – Alejandro Kolio Dec 04 '20 at 17:01
-1

I would say , You can use below on top of you response model class, Which will make your all null and the empty string values not included in json response , Which means the as per json , this will be null.

@Data
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Foo {
    private String a;
    private String b;
}

If a has some value say A and b does not have (It is null or empty), then json response will be ->

{
    "a": "A"
}

Hope you find this useful.

Ajeet Maurya
  • 622
  • 5
  • 16