Openapi generator maven plugin nullable property problem

Viewed 9293

I attempted to introduce nullable properties in an API which has been designed using openapi 3 specifications. The idea is to always return the properties to the client, whether their values are null or not.

YAML file (I tried first without default, with same results):

       property:
          type: integer
          nullable: true
          default: null

Generated Java code:

  @JsonProperty("property")
  private JsonNullable<Integer> property = JsonNullable.undefined();

Response from API:

  "property": {
    "present": true
  }

So the result is always "present: true" whether or not the property is null or not. Without nullability it works out just fine, except for the null values being removed from the response which is undesireable.

Any ideas?

P.S. The property isn't actually named as "property"

Edit: configuration:

<generateAliasAsModel>true</generateAliasAsModel>
<inputSpec>./api/interface1.yaml</inputSpec>
<generatorName>spring</generatorName>
<enablePostProcessFile>true</enablePostProcessFile>
<configOptions>
    <sourceFolder>src/main/java</sourceFolder>
    <library>spring-boot</library>
    <java8>true</java8>
    <interfaceOnly>true</interfaceOnly>
    <useOptional>true</useOptional>
</configOptions>
2 Answers

A property can be mentioned as nullable to pass null value in openApi. OpenApi generator wraps the datatype with JsonNullable as shown below.

private JsonNullable<String> firstField = JsonNullable.undefined();

The response you mentioned in your question says that the property is present but not the real value, this happens when the object is not serialized correctly. Just by registering JsonNullableModule should instruct how to serialize the parser such as jackson.

@Bean
public Module jsonNullableModule() {
   return new JsonNullableModule();
}

At least in the version org.openapitools:jackson-databind-nullable:0.2.1 I do not see such issues, meant no need to register the above been explicitly as it is take care by the library itself.

Thanks to the help of @maniganda-prakash I was able to resolve my issue by registering the module in a custom ObjectMapper that is used by the RestTemplate.

Something like this:

var objectMapper = new ObjectMapper().registerModule(new JsonNullableModule());
var httpMessageConverter = new MappingJackson2HttpMessageConverter(objectMapper);
var restTemplate = RestTemplateBuilder.restTemplate().build();
restTemplate.getMessageConverters().add(0, httpMessageConverter);   
Related