首页 > 解决方案 > Springfox/swagger 忽略 @XmlElements

问题描述

我想为以下控制器添加 swagger API

@RestController
public class MyController {

    @PostMapping("/box")
    public String post(@RequestBody MyBox myBox) {
        return "Success";
    }
}

我实际上正在关注 myBox 示例值:

{
  "BoxName": "string",
  "items": [
    {}
  ]
}

但我需要这样:

{
  "BoxName" : "string",
  "items" : [ {
    "MyItem1" : {
      "name" : "string"
    }
  }, {
    "MyItem2" : {
      "description" : "string"
    }
  } ]
}

MyBox类:

@XmlType(name = "MyBox")
public class MyBox {

    @XmlElement(name = "BoxName")
    protected String boxName;

    @XmlElements({
            @XmlElement(name = "MyItem1", type = MyItem1.class),
            @XmlElement(name = "MyItem2", type = MyItem2.class),
    })
    protected List<Object> items;
}

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "MyItem1")
public class MyItem1 {
    @XmlElement(name = "name")
    private String name;
}

@XmlType(name = "MyItem2")
public class MyItem2 {
    @XmlElement(name = "name")
    private String description;
}

我添加了以下SwaggerObjectMapper配置:

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .alternateTypeRules()
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.demo.rest"))
                .paths(PathSelectors.any())
                .build();
    }
}


@Configuration
public class ApplicationConfiguration {
    @Bean
    @Primary
    public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
        return builder.modules(new JaxbAnnotationModule().setPriority(JaxbAnnotationModule.Priority.PRIMARY))
                .build()
                .enable(SerializationFeature.INDENT_OUTPUT);
    }
}

我无法更改(添加模型映射)到MyBoxMyItem1MyItem2,它们是自动生成的。

我添加了演示项目来重现该问题: https ://github.com/ivan333m/springfox-jaxb

有人可以指出我正确的方向吗?

标签: swaggerswagger-uispringfox

解决方案


推荐阅读