Skip to content

Add support for jackson-databind-nullable #2512

Closed

Description

@noshua

Is your feature request related to a problem? Please describe.

When using springdoc-openapi together with openapi-generator and it's jackson-databind-nullable the generated swagger-ui for nullable fields is broken. Instead of showing the Object attributes only "present": true is displayed.

Describe the solution you'd like

A JsonNullable attribute should be displayed like an Optional. So the Object attributes should be displayed.

Describe alternatives you've considered

And couldn't find any alternatives.

Additional context

grafik
grafik

Activity

  1. bnasslahsen commented on Mar 2, 2024

    @bnasslahsen
    Collaborator

    @noshua,

    This is considered as incomplete enhancement request.
    You need to provide all the points mentioned in the section: Using GitHub Issues

    This ticket will be closed, but can be reopened if your provide all the elements.

  2. added
    incomplete
    on Mar 2, 2024
  3. xak2000 commented on Apr 4, 2024

    @xak2000

    @bnasslahsen Can you please clarify what points you mean exactly?

    I read the contribution docs you mentioned and I do not see any mention of how an enhancement request should be filled.

    I see some points in the section:

    If you are reporting a bug, please help to speed up problem diagnosis by providing as much information as possible

    Maybe that is what you meant? But these points are really more appropriate for bugs, than feature requests. For example, I'm not sure how to provide "Minimal, Reproducible Example" for a feature request. :)

    I'm asking because I want this (or similar) feature too to be implemented (maybe as an additional library if it will be dependent on a class, that doesn't exist in springdoc, e.g. JsonNullable) so I want to understand what information is missing in your opinion.

    I agree that this feature request is far from ideal, so maybe I can explain it better.

    I think the author wants JsonNullable class to be treated exactly as java.util.Optional is currently treated by springdoc. I.e. unwrapped by default, as this is how jackson-databind-nullable works. It provides Jackson serializer/deserializer that authomatically maps JSON string to JsonNullable<String> and vice versa.

    I.e. this model

    public class Pet {
        public JsonNullable<String> name = JsonNullable.undefined();
     }

    should be treated like it was this:

    public class Pet {
        public String name;
     }

    Also it would be very useful to add a recipe to the official FAQ on how to configure springdoc to make a custom "wrapper" class to be automatically treated like Optional (i.e. unwrapped). Personaly I do not use jackson-databind-nullable library and JsonNullable class, but I want to configure my own custom wrapper. Maybe it is easy to do, but the docs do not explain custom configuration capabilities very well, most classes do not even have javadocs, so for now I'm trying to find how it is implemented for Optional and do the same..

  4. xak2000 commented on Apr 4, 2024

    @xak2000

    Answering my own question on how to configure springdoc to make a custom "wrapper" class to be automatically treated like Optional (i.e. unwrapped).

    1. A io.swagger.v3.core.converter.ModelConverter bean should be registered:
    @ConditionalOnProperty(name = SPRINGDOC_ENABLED, matchIfMissing = true)
    @Configuration
    public class ApiDocModelConvertersConfig {
    
    	@Bean
    	ModelConverter nullableOptionalModelConverter(ObjectMapperProvider objectMapperProvider) {
    		return new NullableOptionalModelConverter(objectMapperProvider);
    	}
    
    }

    Springdoc will automatically register all found ModelConverter beans as OpenAPI resolvers (if only this information was mentioned in the docs...).

    1. An example of ModelConverter implementation that unwraps NullableOptional model:
    @Slf4j
    public class NullableOptionalModelConverter implements ModelConverter {
    
    	private final ObjectMapperProvider objectMapperProvider;
    
    	public NullableOptionalModelConverter(ObjectMapperProvider objectMapperProvider) {
    		this.objectMapperProvider = objectMapperProvider;
    	}
    
    	@SuppressWarnings("rawtypes")
    	@Override
    	public Schema resolve(AnnotatedType type, ModelConverterContext context, Iterator<ModelConverter> chain) {
    		AnnotatedType unwrappedType = tryUnwrapNullableOptional(type);
    		if (unwrappedType != null) {
    			return context.resolve(unwrappedType);
    		}
    
    		return chain.hasNext() ? chain.next().resolve(type, context, chain) : null;
    	}
    
    	private AnnotatedType tryUnwrapNullableOptional(AnnotatedType type) {
    		if (type == null) {
    			return null;
    		}
    
    		try {
    			JavaType jtype;
    			if (type.getType() instanceof JavaType) {
    				jtype = (JavaType) type.getType();
    			} else {
    				jtype = objectMapperProvider.jsonMapper().constructType(type.getType());
    			}
    
    			if (NullableOptional.class.isAssignableFrom(jtype.getRawClass())) {
    				return new AnnotatedType()
    						.type(jtype.containedType(0))
    						.name(type.getName())
    						.parent(type.getParent())
    						.jsonUnwrappedHandler(type.getJsonUnwrappedHandler())
    						.skipOverride(type.isSkipOverride())
    						.schemaProperty(type.isSchemaProperty())
    						.ctxAnnotations(type.getCtxAnnotations())
    						.resolveAsRef(type.isResolveAsRef())
    						.jsonViewAnnotation(type.getJsonViewAnnotation())
    						.skipSchemaName(type.isSkipSchemaName())
    						.skipJsonIdentity(type.isSkipJsonIdentity())
    						.propertyName(type.getPropertyName());
    			} else {
    				return null;
    			}
    		} catch (Exception e) {
    			log.error("Error unwrapping NullableOptional", e);
    			return null;
    		}
    	}
    
    }

    NullableOptional is my own class, but the same principle could be used to unwrap any class with generic arguments, such as JsonNullable from jackson-databind-nullable library.

  5. mschout commented on May 1, 2024

    @mschout
    Contributor

    For anyone else, this is my working version of this, that uses JsonNullable:

    1: Register JsonNullable for Jackson somewhere. My solution is this:

    import com.fasterxml.jackson.databind.Module;
    import lombok.extern.slf4j.Slf4j;
    import org.openapitools.jackson.nullable.JsonNullableModule;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    @Slf4j
    public class JacksonConfiguration {
      @Bean
      Module jsonNullableModule() {
        log.info("Configuring Jackson to use JsonNullable as null value");
        return new JsonNullableModule();
      }
    }

    In your DTO, only include NON_NULL items. E.g.:

    @Data
    @JsonInclude(JsonInclude.Include.NON_NULL)
    public class UpdateDTO {
      private Long id;
    
      private JsonNullable<String> name = JsonNullable.undefined();
    }

    And finally, the part to get it working with springdoc-openapi, add a converter configuration class:

    @Configuration
    @Slf4j
    public class JsonNullableApiDocModelConvertersConfig {
      @Bean
      ModelConverter jsonNullableModelConverter(ObjectMapperProvider objectMapperProvider) {
        return new JsonNullableModelConverter(objectMapperProvider);
      }
    
      @RequiredArgsConstructor
      static class JsonNullableModelConverter implements ModelConverter {
        private final ObjectMapperProvider objectMapperProvider;
    
        @Override
        public Schema<?> resolve(AnnotatedType type, ModelConverterContext context, Iterator<ModelConverter> iterator) {
          var unwrappedType = tryUnwrapJsonNullable(type);
          if (unwrappedType != null) {
            return context.resolve(unwrappedType);
          }
    
          return iterator.hasNext()
            ? iterator.next().resolve(type, context, iterator)
            : null;
        }
    
        private AnnotatedType tryUnwrapJsonNullable(AnnotatedType type) {
          var javaType = resolveType(type);
    
          if (JsonNullable.class.isAssignableFrom(javaType.getRawClass())) {
            return new AnnotatedType()
              .type(javaType.containedType(0))
              .name(type.getName())
              .parent(type.getParent())
              .jsonUnwrappedHandler(type.getJsonUnwrappedHandler())
              .skipOverride(type.isSkipOverride())
              .schemaProperty(type.isSchemaProperty())
              .ctxAnnotations(type.getCtxAnnotations())
              .resolveAsRef(type.isResolveAsRef())
              .jsonViewAnnotation(type.getJsonViewAnnotation())
              .skipSchemaName(type.isSkipSchemaName())
              .skipJsonIdentity(type.isSkipJsonIdentity())
              .propertyName(type.getPropertyName());
          }
    
          return null;
        }
    
        private JavaType resolveType(AnnotatedType type) {
          if (type.getType() instanceof JavaType javaType) {
            return javaType;
          }
          else {
            return objectMapperProvider.jsonMapper().constructType(type.getType());
          }
        }
      }
    }
  6. duke1995 commented on May 16, 2024

    @duke1995

    In my case, the solution described in this answer on StackOverflow also works:
    openapi - Incorrect information about JsonNullable in swagger - Stack Overflow

    @Configuration
    public class ObjectMapperConfig {
    
        /**
         * Override default Spring Doc Object mapper provider and add the JsonNullableModule - otherwise the OpenAPI JSON
         * Spec interprets the JsonNullable wrong
         *
         * @param springDocConfigProperties given config properties in application yaml
         * @return provider for spring doc generation
         */
        @Bean
        public ObjectMapperProvider springdocObjectMapperProvider(SpringDocConfigProperties springDocConfigProperties) {
            ObjectMapperProvider objectMapperProvider = new ObjectMapperProvider(springDocConfigProperties);
            objectMapperProvider.jsonMapper().registerModule(jsonNullableModule());
            return objectMapperProvider;
        }
    
        /**
         * Register JsonNullableModule for openapi generation in springdoc (above) and for the default object mapper
         * used to serialize/deserialize JSON Payloads via web requests - otherwise the application is not able to map
         * JsonNullable<Type> fields
         *
         * @return json nullable module
         */
        @Bean
        public Module jsonNullableModule() {
            return new JsonNullableModule();
        }
    
    }
  7. daedrics commented on May 27, 2024

    @daedrics

    Hi @duke1995 ,
    How does your open api generated class look like after adding this configuration? I'm trying to send PATCH requests from the generated api client but I cannot tell the client to not send the fields that I didn't specify.
    Example:
    I have this PatchDTO:

    @Schema(name = "PatchDto")
    @Getter
    @Setter
    @NoArgsConstructor
    public class PatchDto  {
    
        @Schema(description = "Voy status code", implementation = VoyStatusCode.class)
        private JsonNullable<VoyStatusCode> voyStatusCode;
    
        @Schema(description = "Voy Sales", implementation = VoySalesBlocked.class)
        private JsonNullable<VoySalesBlocked> paxSalesBlocked;
    
       @Schema(description = "Name", implementation = String.class)
        private JsonNullable<String> name;
    
    }
    

    When I want to send only the name field the request has also the other two fields as null but I don't want to send them.

  8. suchira19 commented on Jan 30, 2025

    @suchira19

    I am also having the requirement of distinguishing between a missing field in my request vs a field being explicitly set as null. And Jackson mapper is not working with openapi JsonNullableDeserializer. Has anyone able to resolve this?

  9. mschout commented on Feb 4, 2025

    @mschout
    Contributor

    @daedrics your DTO needs to set a default value of JsonNullable.undefined() for each field.

    e.g.

    private JsonNullable<VoyStatusCode> voyStatusCode = JsonNullable.undefined();
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    incomplete

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions