简体   繁体   English

如何在生成Swagger文档时让Springfox序列化jaxb注释模型

[英]How to get Springfox to serialize jaxb annotated models when generating Swagger documentation

I've been trying to document my spring-boot API as a Swagger document using Springfox, but I can't figure out how to get it to serialize my jaxb annotated models (which are from a maven dependency, so are read-only). 我一直在尝试使用Springfox将我的spring-boot API记录为Swagger文档,但是我无法弄清楚如何使用它来序列化我的jaxb注释模型(它们来自maven依赖,因此是只读的) 。 I've done a whole lot of searching on here, and the Springfox github page and documentation and can't seem to figure it out. 我在这里做了很多搜索,而Springfox github页面和文档似乎无法弄明白。 I've tried a host of different swagger annotations on my controller as well, but mostly I got a class not found exception because it couldn't find a class ApiImplicitParam, which I didn't even use. 我也在我的控制器上尝试了许多不同的swagger注释,但大多数时候我找到了一个未找到类的异常,因为它找不到类ApiImplicitParam,我甚至没有使用它。 Any help would be appreciated. 任何帮助,将不胜感激。

Here is my handler: 这是我的处理程序:

  @RequestMapping(
  value = "/GnAcctDetailsInq",
  consumes = MediaType.APPLICATION_JSON_VALUE,
  produces = MediaType.APPLICATION_JSON_VALUE,
  method = RequestMethod.POST
  )
  public ResponseEntity<GnAcctDetailsInqResponse> gnAcctDetailsInq(
      @RequestHeader HttpHeaders requestHeaders, @RequestBody GnAcctDetailsInqRequest request)
      throws ClassNotFoundException, XmlMappingException, IOException, MessengerException,
      AuthException {
    log.info("Sending request message: {}", request);
    String xmlResponse = autoapiService.sendAndReceive(requestHeaders, request);
    GnAcctDetailsInqResponse domainObjectResponse = (GnAcctDetailsInqResponse) autoapiService.convert(xmlResponse);
    HttpHeaders responseHeaders = autoapiService.createResponseHeaders(domainObjectResponse);
    return new ResponseEntity<GnAcctDetailsInqResponse>(domainObjectResponse, responseHeaders, HttpStatus.ACCEPTED);
  }

My Springfox Swagger configuration: 我的Springfox Swagger配置:

@Bean
public Docket autoapi() {

List<ResolvedType> otherModels = getNonGnModels();

return new Docket(DocumentationType.SWAGGER_2)
    .select()
        .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
        .paths(PathSelectors.any())
        .build()
    .pathProvider(new RelativePathProvider(servletContext) {
        @Override
        public String getApplicationBasePath() {
            return "/autoapi";
        }
    })
    .genericModelSubstitutes(ResponseEntity.class)
    .alternateTypeRules(
            newRule(typeResolver.resolve(DeferredResult.class,
                    typeResolver.resolve(ResponseEntity.class, WildcardType.class)),
                    typeResolver.resolve(WildcardType.class)))
    // This method expects the first argument to be only one instance of a ResolvedType, the second one can be an array.
    .additionalModels(typeResolver.resolve(Error.class)
            , otherModels.toArray(new ResolvedType[otherModels.size()]));       
}

And I'm fairly certain I configured the object mapper as it is supposed to be as well: 而且我相当确定我配置了对象映射器,因为它应该也是如此:

@EnableWebMvc
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

    @Bean
    @Primary
    public ObjectMapper objectMapper() {

        return new ObjectMapper()
            .registerModules(new JaxbAnnotationModule())
            .setSerializationInclusion(Include.NON_NULL)
            .enable(SerializationFeature.INDENT_OUTPUT)
            .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
            .enable(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT)
            .enable(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY)
            .enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT)
            .enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES)
            .enable(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES)
            .enable(JsonParser.Feature.ALLOW_MISSING_VALUES);
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> messageConverters) {
        messageConverters.add(new MappingJackson2HttpMessageConverter(objectMapper()));
    }

    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        ObjectMapper objectMapper = null;
        for (HttpMessageConverter<?> converter : converters) {
            if (converter instanceof MappingJackson2HttpMessageConverter) {
                MappingJackson2HttpMessageConverter jacksonConverter =
                        ((MappingJackson2HttpMessageConverter) converter);

                if (objectMapper == null) {
                    objectMapper = jacksonConverter.getObjectMapper();
                } else {
                    jacksonConverter.setObjectMapper(objectMapper);
                }
            }
        }
    }
}

Also, this is how the model for the response Object looks -- they are all pretty similar, some have fields where they refer to another one of my models, others are just objects with String and int field. 此外,这是响应对象的模型看起来 - 它们都非常相似,有些具有引用我的另一个模型的字段,其他只是具有String和int字段的对象。

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {"accountInfo", "requestStatus"})
@XmlRootElement(name = "gnAcctDetailsInqResponse")
public class GnAcctDetailsInqResponse implements Serializable {
    @XmlElement(name = "AccountInfo")
    protected AccountInfo accountInfo;
    @XmlElement(name = "RequestStatus", required = true)
    protected RequestStatus requestStatus;

    public AccountInfo getAccountInfo() {
        return this.accountInfo;
    }

    public void setAccountInfo(AccountInfo value) {
        this.accountInfo = value;
    }

    public RequestStatus getRequestStatus() {
        return this.requestStatus;
    }

    public void setRequestStatus(RequestStatus value) {
        this.requestStatus = value;
    }
}

This model, like others is represented in the Swagger doc as: 与其他模型一样,此模型在Swagger文档中表示为:

"GnAcctDetailsInqResponse": {
  "type": "object",
  "title": "GnAcctDetailsInqResponse",
  "xml": {
    "name": "GnAcctDetailsInqResponse",
    "attribute": false,
    "wrapped": false
  }

I have also made a json schema generator by altering some of the jackson-module-jsonSchema code that serializes my models as I wish, would it be possible to somehow inject those schema definitions inside the definitions object of the Swagger doc? 我还通过改变一些按照我的意愿序列化我的模型的jackson-module-jsonSchema代码制作了一个json模式生成器,是否有可能以某种方式将这些模式定义注入到Swagger doc的定义对象中? I'm open to any type of solution. 我对任何类型的解决方案持开放态度。

After a little further investigation I noticed the only types that have their fields serialized are ones where the fields aren't annotated with @XmlElement 经过一番进一步的调查后,我发现只有序列化字段的类型才是字段没有用@XmlElement注释的字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 Springfox 从 Swagger 文档中隐藏端点 - How to hide endpoints from Swagger documentation with Springfox 没有捕获Springfox Swagger配置和文档 - Springfox Swagger Configuration and Documentation not being captured 昂首阔步不生成REST文档 - Swagger not generating the REST documentation 如何从application.properties设置springfox.documentation.swagger.v2.path - how to set the springfox.documentation.swagger.v2.path from application.properties 如何在openApi / springfox-swagger2中为不同的状态代码定义不同的响应模型 - How to define different response models for different status codes in openApi / springfox-swagger2 用Swagger进行发音-使用泛型时无法生成文档资源模型 - Enunciate with Swagger - cannot generate documentation resource models when using generics 如何获取所有Jackson / JAXB带注释的属性值? - How to get all Jackson/JAXB annotated property values? Swagger (Springfox) 只找到控制器 @RequestBody (Spring Boot) 中使用的模型 - Swagger (Springfox) only finding Models used in Controller @RequestBody (Spring Boot) Swagger2:无法自省 Class [springfox.documentation.swagger2.configuration.Swagger2DocumentationConfiguration] - Swagger2: Failed to introspect Class [springfox.documentation.swagger2.configuration.Swagger2DocumentationConfiguration] Springfox Swagger 如何配置命令属性? - Configure how Springfox Swagger orders properties?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM