Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JsonNullable is not serializing its value with Jackson

Tags:

java

json

I'm trying to use JsonNullable<String> to distinguish between the absence of a value and null. When I serialize my Java object, User, the JsonNullable<String> field is serialized as a JSON object with value

{"present":false}

I'm expecting it to print {} since I initialized the field with undefined.

Here's my class

public class User { 
  @JsonProperty("userId")
  private JsonNullable<String> userId = JsonNullable.undefined();

  //set and get
  //tostring
}

and a small driver program where I actually set a value within the JsonNullable field.

User user = new User();
user.setUserId(JsonNullable.of("12345"));

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new Jdk8Module());

String expectedData = objectMapper.writeValueAsString(user);
System.out.println(expectedData);

This prints

{"userId":{"present":true}}

But I expected

{"userId":"12345"}

In other words, I expected the value wrapped within the JsonNullable to be serialized into the JSON. Why are JsonNullable and Jackson behaving this way?

like image 450
Surya Prakash Avatar asked Jan 25 '23 15:01

Surya Prakash


2 Answers

As the wiki instructs, you need to register the corresponding module (in addition to any others you have):

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
objectMapper.registerModule(new JsonNullableModule());
like image 98
Sotirios Delimanolis Avatar answered Jan 30 '23 03:01

Sotirios Delimanolis


Add the following configuration in Spring Boot:

@Configuration
public class JacksonConfiguration {
    @Bean
    public JsonNullableModule jsonNullableModule() {
        return new JsonNullableModule();
    }
}
like image 37
akasha Avatar answered Jan 30 '23 03:01

akasha