Brucebayne
Brucebayne

Reputation: 39

Optional<?> field in java class, model, not showing on swagger ui

I have set up a swagger on my spring boot application, where on a lot of methods and controllers works correctly. The problem is the one field in the response class where Optional field is not showing on UI.

public class CalculatedResult {
    private CalculatorKey key;
    private CalculatedField field;
    **@ApiModelProperty(value = "Depending on CalculatedField it can be number or string")
    private Optional<?> value;**

... getters setters and etc

And the swagger class:

@Bean
public Docket api() {
    //global default message that are on all methods
    List<ResponseMessage> globalMessages = Arrays.asList(GLOBAL_MESSAGES); // ignore this
    
    return new Docket(DocumentationType.SWAGGER_2)
            .select()      
            .apis(RequestHandlerSelectors.basePackage("pts.riskengine"))
            .paths(PathSelectors.any())   
            .build()
            .directModelSubstitute(LocalDate.class, String.class)
            .genericModelSubstitutes(ResponseEntity.class)
            .alternateTypeRules(
                    newRule(typeResolver.resolve(DeferredResult.class,
                            typeResolver.resolve(ResponseEntity.class, WildcardType.class)),
                            typeResolver.resolve(WildcardType.class)))
            .additionalModels(typeResolver.resolve(ClientSettings.class), typeResolver.resolve(CalculatedResult.class),
                    typeResolver.resolve(CalculatorKey.class))
            .useDefaultResponseMessages(false)
            .forCodeGeneration(true)
            .apiInfo(apiInfo())
            .securitySchemes(Arrays.asList(securityScheme()))
            .securityContexts(Arrays.asList(securityContext()))
            .globalResponseMessage(RequestMethod.GET, globalMessages)
            .globalResponseMessage(RequestMethod.POST, globalMessages)
            .globalResponseMessage(RequestMethod.PUT, globalMessages)
            .globalResponseMessage(RequestMethod.DELETE, globalMessages)
            ;
}

I have tried to put in .additionalModels and also in .genericModelSubstitutes as String, but not working. dataType = "java.lang.String" is also not solving my issue. Do anyone else got this kind of problem or know how it could be solvable ?

Looking on UI: Screenshot

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>   

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.8.0</version>
    <scope>compile</scope>
</dependency>

Upvotes: 0

Views: 1043

Answers (1)

mbehram
mbehram

Reputation: 71

Optional class is not serializable. That's why swagger is not showing Optional.

https://stackoverflow.com/a/24564612/19008623

Upvotes: 1

Related Questions