Skip to content

Setting example value 'null' to fields in json request body with @Schema, not "null" string without model converter #4767

Open
@infomuscle

Description

Hello,

While I was making an API document, I struggled to set value of fields to 'null' in json request body.
I used @Schema annotation because I was in spring boot and kotlin.

At first, I thought that setting "null" in an attribute like defaultValue or example would be helpful.
But it showed "null" string.
So I searched it on the Internet because I thought many people would have faced same issue with me.
With help of Generative AI, I finally found that ModelConverter could solve my issue and solved it.
Below is the way I solved.

@Configuration
class SwaggerConfiguration {
    @Bean
    fun customModelConverter(): CustomModelConverter {
        return CustomModelConverter()
    }

}

class CustomModelConverter : ModelConverter {
    override fun resolve(type: AnnotatedType, context: ModelConverterContext, chain: Iterator<ModelConverter>, ): Schema<*>? {
        var schema: Schema<*>? = null
        while (chain.hasNext()) {
            schema = chain.next().resolve(type, context, chain)
            if (schema.example == "null") {
                schema.example = null
            }
        }

        return schema
    }
}

But It seems that it can be solved in easier way.
For example, in JUnit, @CSVSource can pass argument as null with nullValues attribute.
Below is the sample code, which converts "null" string to null.

@CsvSource(value= {"null"}, nullValues={"null"})

Or it can be set to null if nullable is true and example is not defined.

I'm curious that this issue is being considered to be solved
or many people are satisfied with using model converter
or there is another way to handle it in easier.

Thank you.

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions