Giter Site home page Giter Site logo

openapitools / jackson-databind-nullable Goto Github PK

View Code? Open in Web Editor NEW
92.0 92.0 31.0 113 KB

JsonNullable wrapper class and Jackson module to support meaningful null values

License: Apache License 2.0

Java 100.00%
jackson jackson-databind nullable optional

jackson-databind-nullable's People

Contributors

animalet avatar bkabrda avatar bratkartoffel avatar cbornet avatar dependabot[bot] avatar hatzlj avatar jmini avatar joschi avatar julianladisch avatar melled avatar pascalschumacher avatar plum117 avatar tofi86 avatar wing328 avatar zteater avatar zwoca avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jackson-databind-nullable's Issues

Add Jackson ServiceLoader support

It would be great if you could add support for the ServiceLoader of Jackson, to make it easier to register the module with Jackson (e.g. allowing ObjectMapper#findAndRegisterModules to find this module).

It should suffice to add a file named com.fasterxml.jackson.databind.Module with the content org.openapitools.jackson.nullable.JsonNullableModule to the META-INF/servcies folder of the jar.

By the way: Thank you for providing jackson-databind-nullable! ๐Ÿ‘

How to use this with Spring Boot

I generated the client code from my OAS 3.0.3 spec for java, resttemplate and java8 as dateLibrary.

I had to explicitly set openApiNullable to true in the gradle plugin - otherwise I had to manually add this dependency to the generated build.gradle.

My spring boot 2.3.x app has a configuration:

@Configuration
public class JacksonConfiguration {

    @Bean
    public ObjectMapper objectMapper() {
        final ObjectMapper m = new ObjectMapper();
        m.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        m.registerModule(new JsonNullableModule());
        return m;
    }

    @Bean
    public HttpMessageConverters httpMessageConverters() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        mapper.registerModule(new JsonNullableModule());
        return new HttpMessageConverters(new MappingJackson2HttpMessageConverter(mapper));
    }

}

that I explicitly import:

@Import({JacksonConfiguration.class})

But I just keep hitting

Caused by: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `org.openapitools.jackson.nullable.JsonNullable` (no Creators, like default constructor, exist): no String-argument constructor/factory method to deserialize from String value
...
        at com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:67) ~[jackson-databind-2.11.2.jar!/:2.11.2]
        at com.fasterxml.jackson.databind.DeserializationContext.reportBadDefinition(DeserializationContext.java:1615) ~[jackson-databind-2.11.2.jar!/:2.11.2]
        at com.fasterxml.jackson.databind.DatabindContext.reportBadDefinition(DatabindContext.java:400) ~[jackson-databind-2.11.2.jar!/:2.11.2]
        at com.fasterxml.jackson.databind.DeserializationContext.handleMissingInstantiator(DeserializationContext.java:1077) ~[jackson-databind-2.11.2.jar!/:2.11.2]
        at com.fasterxml.jackson.databind.deser.ValueInstantiator._createFromStringFallbacks(ValueInstantiator.java:371) ~[jackson-databind-2.11.2.jar!/:2.11.2]
        at com.fasterxml.jackson.databind.deser.std.StdValueInstantiator.createFromString(StdValueInstantiator.java:323) ~[jackson-databind-2.11.2.jar!/:2.11.2]
        at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromString(BeanDeserializerBase.java:1408) ~[jackson-databind-2.11.2.jar!/:2.11.2]
        at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:176) ~[jackson-databind-2.11.2.jar!/:2.11.2]
        at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:166) ~[jackson-databind-2.11.2.jar!/:2.11.2]
        at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:129) ~[jackson-databind-2.11.2.jar!/:2.11.2]
        at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:371) ~[jackson-databind-2.11.2.jar!/:2.11.2]
        at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:164) ~[jackson-databind-2.11.2.jar!/:2.11.2]
        at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:129) ~[jackson-databind-2.11.2.jar!/:2.11.2]
        at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:371) ~[jackson-databind-2.11.2.jar!/:2.11.2]
        at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:164) ~[jackson-databind-2.11.2.jar!/:2.11.2]
        at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:291) ~[jackson-databind-2.11.2.jar!/:2.11.2]
        at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:250) ~[jackson-databind-2.11.2.jar!/:2.11.2]
        at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:27) ~[jackson-databind-2.11.2.jar!/:2.11.2]
        at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:129) ~[jackson-databind-2.11.2.jar!/:2.11.2]
        at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:371) ~[jackson-databind-2.11.2.jar!/:2.11.2]
        at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:164) ~[jackson-databind-2.11.2.jar!/:2.11.2]
        at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4524) ~[jackson-databind-2.11.2.jar!/:2.11.2]
        at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3519) ~[jackson-databind-2.11.2.jar!/:2.11.2]
        at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:273) ~[spring-web-5.2.8.RELEASE.jar!/:5.2.8.RELEASE]
        ... 24 common frames omitted

Allow javax.validation for JsonNullable for constraints supported by openapi

When using a Constraint (e.g. size) on a nullable element, you will get the following exception

javax.validation.UnexpectedTypeException: HV000030: No validator could be found for constraint 'javax.validation.constraints.Size' validating type 'org.openapitools.jackson.nullable.JsonNullable<java.lang.String>'. Check configuration for 'data[0].message'

since there is no Validator for JsonNullable supporting the javax.validation.constraints.Size constraint.

We're currently testing a solution for this, declaring the necessary validators via META-INF/services. Since the JsonNullable is defined in jackson-databind-nullable i would suggest to include appropriate validators (including size and others) also in the jackson-databind-nullable module and expose them via the META-INF/services/javax.validation.ConstraintValidator to automatically support bean validation generated by the openapi-generator.

Before submitting a PR, i'd like to discuss the following questions:
-> is this module the right place for the validators (we would be adding a dependency on the javax.validation api, but without validators for json nullable you cannot use constraints in your api definition together with nullable)
-> which constraints do we need to support with validators (i.e. which constraints are currently supported by the openapi-java-generators)

Compatibility issue with spring boot 3 / jakarta api

Hi,

thanks for this great plugin! AS spring boot 3.0 was released yesterday, I tried to upgrade my project to that new version. This upgrade also includes the change from javax -> jakarta api, which I think breaks this library.

Version 0.2.4 does not work with the jakarta-api:

// this configuration worked fine with boot 2.7.6

@Configuration
public class JacksonNullableModuleConfiguration {
    @Bean
    public JsonNullableModule jsonNullableModule() {
        return new JsonNullableModule();
    }
}
jakarta.servlet.ServletException: Request processing failed: jakarta.validation.UnexpectedTypeException: HV000030: No validator could be found for constraint 'jakarta.validation.constraints.Size' validating type 'org.openapitools.jackson.nullable.JsonNullable<java.lang.String>'. Check configuration for 'password'

	at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1011)
	at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:877)

Changing that configuration like proposed by #18 (comment) results in another exception:

@Configuration
public class JacksonNullableModuleConfiguration {
    @Bean
    public JsonNullableModule jsonNullableModule(ObjectMapper objectMapper) {
        JsonNullableModule module = new JsonNullableModule();
        objectMapper.registerModule(module);
        return module;
    }
}
Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'jsonNullableModule': Requested bean is currently in creation: Is there an unresolvable circular reference?
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.beforeSingletonCreation(DefaultSingletonBeanRegistry.java:355)
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:227)
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:324)

Can you please make it work with the jakarta-validation annotations as it did with the java-validation annotations?

Thanks,
Simon

Custom deserializer and empty string treatment

In our scenario, we have an API that for a field reports an empty String. The empty String should be deserialized to an enum value that represents the scenario of emptry String: "" -> ConstaintType.NONE (yes, I know this is weird).

I noticed that it however did not end up in our custom deserializer that handles this mapping. The reason for that is that JsonNullableDeserializer#deserialize(JsonParser, DeserializationContext) catches the scenario for empty string and maps it to JsonNullable.undefined(). This logic currently happens if the deserializer is not a String deserializer (there is an open PR that extends it to CharSequence #45).

In my opinion, it is being a bit too smart here. I would expect that it always delegates to super; or at least only return JsonNullable.undefined for the standard Java types and delegate to super.deserialize for the custom user defined Java classes? At minimum, it would be nice if we could easily override this behaviour?

Add convenient Optional.orElse() like getter to JsonNullable

First of all thanks for including the nullable support in OpenAPITools.
I would like to suggest a minor improvement to the API of JsonNullable.

Currently we would need to use something like

jsonNullableString.isPresent() ? jsonNullableString.get() : null

to allow inline usage of the value.

Having someting like java Optional's .orElse() would make inline usage of JsonNullable easier.

public T orElse(T other) {
  return this.isPresent ? this.value : other;
}        

What do you think? If you like this idea, I would be happy to submit a PR to this project.

thanks,
Jakob

Does it work with current SpringBootStarter 3.1.x ?

Hi there,

I'm using the module (version 0.2.6) in combination with the openapi-generator plugin.

However I seem to have problems to map json responses from the called system (via restTemplate), which does not provide the JsonNullable json representation but the plain attributes and crashes when trying to map a String to JsonNullable on the generated DTO.

My jackson mapper doesn't seem to be convinced to do such a mapping, this is the config I'm using

@Configuration
public class JacksonMapperConfiguration {

    @Bean
    public RestTemplate createRestTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        converter.setObjectMapper(jackson2ObjectMapperBuilder().build());
        restTemplate.getMessageConverters().add(0, converter);
        return restTemplate;
    }

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

    @Bean
    public Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder() {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ISO_INSTANT;
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
        SimpleModule module = new SimpleModule();
        module.addDeserializer(JsonNullable.class, new JsonNullableDeserializer(JsonNullable.class));

        builder
            .modules(module, jsonNullableModule(), new JavaTimeModule())
            .serializationInclusion(JsonInclude.Include.NON_NULL)
            .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
            .serializerByType(OffsetDateTime.class,
                    new CustomOffsetDateTimeSerializer(dateTimeFormatter));

        return builder;

    }

and this is the JsonNullabeDeserializer:

public class JsonNullableDeserializer extends JsonDeserializer<JsonNullable<?>> {
    private final Class<?> targetClass;

    public JsonNullableDeserializer(Class<?> targetClass) {
        this.targetClass = targetClass;
    }

    @Override
    public JsonNullable deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        JsonToken jsonToken = jsonParser.currentToken();
        if (jsonToken == JsonToken.VALUE_NULL) {
            return JsonNullable.undefined();
        } else {
            Object value = jsonParser.getCodec().readValue(jsonParser, this.targetClass);
            return JsonNullable.of(value);
        }
    }
}

Having this setup I encounter the following error:

There was an error while trying report the recently mapped BRIDs
org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class org.openapitools.jackson.nullable.JsonNullable]
	at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:403)
	at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:354)
	at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:103)
	at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:1132)
	at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:1115)
	at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:865)
	at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:764)
	at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:646)

[....]

Caused by: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `org.openapitools.jackson.nullable.JsonNullable` (no Creators, like default constructor, exist): no String-argument constructor/factory method to deserialize from String value ('simulated response from the Mock')

To me it looks like the Deserializer isn't called at all. Hm, I set a breakpoint into the firstline of the provided deserializer and it doesn't stop. So it might be more a configuration issue of the Jackson2ObjektMapperBuilder....

Confusion with setSerializationInclusion(Include.NON_NULL)

I'm confused with setup in "Usage section":


ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.registerModule(new JsonNullableModule());

Please take a look on the following snippet ( val=null is passed in JSON and in Map):

record A (JsonNullable<BigDecimal> val) {}
ObjectMapper objectMapper = new ObjectMapper().registerModule(new JsonNullableModule());

A a1 = objectMapper.readValue("{ \"val\" : null }", A.class);
System.out.println(a1);

HashMap hashMap = new HashMap();
hashMap.put("val", null);
A a2 = objectMapper.convertValue(hashMap, A.class);
System.out.println(a2);

Output is consistent

A[val=JsonNullable[null]]
A[val=JsonNullable[null]]

But with setup

ObjectMapper objectMapper = new ObjectMapper().registerModule(new JsonNullableModule())
        .setSerializationInclusion(JsonInclude.Include.NON_NULL);

Output is not consistent

A[val=JsonNullable[null]]
A[val=JsonNullable.undefined]

Well, time for questions:

  1. I do not understand why you propose in "Usage" section setup .setSerializationInclusion(JsonInclude.Include.NON_NULL). It looks useless.
  2. I do not understand how serialization setup may affect deserialization (objectMapper.convertValue is deserialization)

empty string / whitespace string in json should not be JsonNullable.undefined() for JsonNullable<String>

I had some trouble understanding the rationale behind

@Override
public JsonNullable<Object> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
JsonToken t = p.getCurrentToken();
if (t == JsonToken.VALUE_STRING && !_fullType.isTypeOrSubTypeOf(String.class)) {
String str = p.getText().trim();
if (str.isEmpty()) {
return JsonNullable.undefined();
}
}
return super.deserialize(p, ctxt);
}

and took a closer look on the code and tests. I think that the check in line 40 should compare the generic type of JsonNullable rather than the _fullType - otherwise it would replace empty/whitespace strings with JsonNullable.undefined() for any type, since _fullType always is JsonNullable in the Deserializer.

Unfortunately there was no test covering the null/empty string case for JsonNullable, so this behaviour kept undiscovered.

I`ll submit a pull request to fix that bug / add additonal tests to cover the case and would be happy to see it upstream soon if you agree.

Thanks,
Jakob

JsonNullable with Collection is broken

With the version >0.25 the Collection handling is broken.

When you use for example JsonNullable<Set> the extractor (JsonNullableValueExtractorHelper) throws a error.

Caused by: java.lang.ClassCastException: class java.lang.Long cannot be cast to class java.util.Collection (java.lang.Long and java.util.Collection are in module java.base of loader 'bootstrap')
	at org.hibernate.validator.internal.constraintvalidators.bv.size.SizeValidatorForCollection.isValid(SizeValidatorForCollection.java:23)
	at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateSingleConstraint(ConstraintTree.java:180)
	... 156 more

javax.validation.ValidationException: HV000028: Unexpected exception during isValid call.
	at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateSingleConstraint(ConstraintTree.java:186)
	at org.hibernate.validator.internal.engine.constraintvalidation.SimpleConstraintTree.validateConstraints(SimpleConstraintTree.java:62)
	at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:75)
	at org.hibernate.validator.internal.metadata.core.MetaConstraint.doValidateConstraint(MetaConstraint.java:130)
	at org.hibernate.validator.internal.metadata.core.MetaConstraint.access$100(MetaConstraint.java:39)
	at org.hibernate.validator.internal.metadata.core.MetaConstraint$TypeParameterValueReceiver.doValidate(MetaConstraint.java:246)
	at org.hibernate.validator.internal.metadata.core.MetaConstraint$TypeParameterValueReceiver.indexedValue(MetaConstraint.java:212)
	at org.openapitools.jackson.nullable.JsonNullableValueExtractorHelper.extractValues(JsonNullableValueExtractorHelper.java:13)
	at org.openapitools.jackson.nullable.JsonNullableValueExtractor.extractValues(JsonNullableValueExtractor.java:14)
	at org.openapitools.jackson.nullable.JsonNullableValueExtractor.extractValues(JsonNullableValueExtractor.java:10)
	at org.hibernate.validator.internal.engine.valueextraction.ValueExtractorHelper.extractValues(ValueExtractorHelper.java:42)
	at org.hibernate.validator.internal.metadata.core.MetaConstraint.validateConstraint(MetaConstraint.java:117)
	at org.hibernate.validator.internal.engine.ValidatorImpl.validateMetaConstraint(ValidatorImpl.java:555)
	at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForSingleDefaultGroupElement(ValidatorImpl.java:518)
	at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForDefaultGroup(ValidatorImpl.java:488)
	at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForCurrentGroup(ValidatorImpl.java:450)
	at org.hibernate.validator.internal.engine.ValidatorImpl.validateInContext(ValidatorImpl.java:400)
	at org.hibernate.validator.internal.engine.ValidatorImpl.validate(ValidatorImpl.java:172)
	at org.springframework.validation.beanvalidation.SpringValidatorAdapter.validate(SpringValidatorAdapter.java:109)

Example:


  @JsonProperty("groups")
  @Valid
  private JsonNullable<Set<Long>> groups = JsonNullable.undefined();

@tofi86 Think it is related to you change JsonNullable handling

EDIT: Ok i see there is a longer message, but no solution.
#35

But currently this crashes the open api generator with spring boot.

Craft new release

Thanks for applying my changes, can you please create a new release within the next days?

New Method isUndefined

Hey,

@cbornet convinced me, it's really better to use the JsonNullable instead of Optionals.
From the discussion here OpenAPITools/openapi-generator#3214, the question: Make it sense to create a new method isUndefined()

@JsonIgnore
public boolean isUndefined(){
    return UNDEFINED.equals(this);
}

Before i create a PR, is there a reason why we should not create this method?

Deserialising an empty character as json null instead of json undefined

Recently we changed a type in one object from JsonNullable<String> sth = JsonNullable.undefined() to JsonNullable<Character> sth = JsonNullable.undefined(). Soon after we noticed a change in the deserialisation behaviour - explicit updates of that property to an empty string ("") no longer worked, as they were treated as not present (JsonNullable.undefined instead of JsonNullable[null]).

It seems that the issue is in the JsonNullableDeserializer, namely in the constructor:

this.isStringDeserializer = ((ReferenceType) fullType).getReferencedType().isTypeOrSubTypeOf(String.class);

Does it make sense to change the check and include Character as well as String? Or would you suggest another alternative? If it is the former, we can also open a PR, as the change doesn't seem so large (and there is already #4 for inspiration).

Usage of jackson-databind-nullable with openapi generator plugin

Hi Team,

Sorry if my question is redundant, I would like to know we can use this module with openapi generator plugin from swagger. Suppose I have field email and I want it to be JsonNullable as its optional field and would like to see whether its present or not.

/Mudassar

No need to validate values for JsonNullable.undefined()

At the moment value initialized as undefined() is treated as null within validation.

Following code demonstrates issue:

    public class TestObject {
        @NotNull @Size(max = 3)
        private JsonNullable<String> restrictedString = JsonNullable.undefined();

        public void setRestrictedString(String value) {
            restrictedString = JsonNullable.of(value);
        }
    }
TestObject testObject = new TestObject();
Set<ConstraintViolation<TestObject>> violations = validator.validate(testObject);
assertEquals(0, violations.size());

Here violations should be empty, because JSR380 constraints address value within JsonNullable container, not container itself. So testObject is valid. But actual behavior gives violations.

The openapi swagger codegen generates JsonNullable type fields if the type attribute in swagger is not mentioned. How to overcome this without modifying the swagger. I want JsonNullable for other fields except few.

The openapi swagger codegen generates JsonNullable type fields if the type attribute in swagger is not mentioned. How to overcome this without modifying the swagger. I want JsonNullable for other fields except few.

Sample Swagger:
openapi: 3.0.3
components:
schemas:
Filter:
required:
- name
- value
type: object
properties:
name:
title: Name
type: string
value:
title: Value

In the above sample swagger, the value field is generated as JsonNullable. But i want it to be created as Object type. How to handle this without changing the swagger. Also i dont want to disable JsonNullable for entire swagger. is there a way to achieve this?

Allow to suppress null values in serialization

In order to minimize my response body size from my REST controllers, I would like to be able to supress all null values when serializing to JSON, however when I changed my ObjectMapper to use Include.NON_NULL by default I found that suppressNull is hard coded to false in JsonNullableSerializer. This results in considerable bloat.

You might wonder why I don't use JsonNullable.undefined() instead. I have an OpenAPI schema with 679 different fields, of which 174 are nullable. Keeping track of which fields are nullable, and changing all of those converter classes to use JsonNullable is quite a lot of work. On top of that, the Java models generated with openapi-generator-maven-plugin do not create fluent setters for JsonNullable.

It would save me a lot of effort if JsonNullableSerializer would just respect suppressNull, is that something you would agree to change?
If not, I could submit a PR to add a setting to JsonNullableModule to toggle whether suppressNull should be respected?

JsonNullableDeserializer incompatible with Jackson 2.13

Jackson added getAbsentValue to its API in version 2.13, which is used when a field is absent. The current version of JsonNullableDeserializer, however, does not implement this method. This results in getNullValue being called, which in turn creates invalid deserialization results.

As the latest versions of Spring Boot use Jackson version > 2.13, this library is essentially unusable in its current form when it comes to new/up to date projects.

See FasterXML/jackson-databind#3214.

Vulnerabilities in jackson-databind 2.9.10.6

See https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind

The in v0.2.2 the dependency tree includes jackson-databind 2.9.10.6:

$ mvn dependency:tree -Dincludes=com.fasterxml.jackson.core

[INFO] \- org.openapitools:jackson-databind-nullable:jar:0.2.2:compile
[INFO]    \- com.fasterxml.jackson.core:jackson-databind:jar:2.9.10.6:compile
[INFO]       \- com.fasterxml.jackson.core:jackson-core:jar:2.9.10:compile

This currently has over a dozen known vulnerabilities, some of which are listed with high severity โ€“ mvnrepository lists 15, the owasp dependency scanner 16:
grafik

Just tested with fixing the dependency to v2.9.10.8, which seems to be fine (owasp dependency scanner does not report it anymore).

So the obvious recommendation is to upgrade.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.