从Swagger响应中排除模型或属性

22

我在我的Apache CXF项目中使用了Swagger,使用了@Api、@ApiOperation和@ApiParam注解,并为REST服务生成了API文档。

但是我想从模型属性或完整模块或属性中排除一些字段,例如EntityTag、StatusType和MediaType等。

如何实现这一点?

我从数据库中获取数据并将其设置为用户对象,然后将该用户对象传递给JAX-RS响应构建器。

以下是我的DTO对象之一:

  @ApiModel
  public class User{
  private String name;
   private String email;


 @ApiModelProperty(position = 1, required = true, notes = "used to display user name")
 public int getName() {
    return name;
 }

 public void setName(String name) {
    this.name= name;
}

@ApiModelProperty(position = 2, required = true, notes = "used to display user email")
public int getEmail() {
    return email;
}

 public void setEmail(String email) {
    this.email= email;
 }

现在我在Swagger返回的 JSON 格式中看不到 User 对象的字段或属性。

我的服务类方法响应是:

    @GET
    @ApiOperation(value = "xxx", httpMethod = "GET", notes = "user details", response =  Response.class)
   public Response getUserInfo(){
        User userdto = userdaoimpl.getUserDetails();
        ResponseBuilder builder = Response.ok(user, Status.OK), MediaType.APPLICATION_JSON);
        builder.build();
 }


<bean id="swaggerConfig" class="com.wordnik.swagger.jaxrs.config.BeanConfig">
    <property name="resourcePackage" value="com.services.impl" />
    <property name="version" value="1.0.0" />
    <property name="basePath" value="http://localhost:8080/api" />
    <property name="license" value="Apache 2.0 License" />
    <property name="licenseUrl"
        value="http://www.apache.org/licenses/LICENSE-2.0.html" />
    <property name="scan" value="true" />
 </bean>

你使用的swagger-core版本是哪个? - Ron
2个回答

40

首先,您应该升级到最新的swagger-core版本,目前是1.3.12(您正在使用非常旧的版本)。

您有3种方法来隐藏属性:

  1. 如果您正在使用JAXB注释,可以使用@XmlTransient
  2. 如果您正在使用Jackson,则可以使用@JsonIgnore
  3. 如果您没有使用任何一种方式,或者不想影响模型的一般序列化/反序列化,可以使用Swagger的@ApiModelPropertyhidden属性

请注意,您可能需要将这些设置在getter/setter上,而不是在属性本身上。尝试更改定义以查看哪种方法适用于您。

关于User模型的问题,问题在于您没有从@ApiOperation引用它(您也不需要httpMethod属性)。请尝试按以下方式更改它:

@ApiOperation(value = "xxx", notes = "user details", response =  User.class)

1
这些字段是DTO对象的一部分。swagger-core不会发明字段 ;) - Ron
1
我不明白你所说的“inside model”是什么意思。你说你成功地隐藏了字段,所以我不确定你想解决什么问题。 - Ron
我已经在更新的代码中发布了DTO对象,即User.java。请查看我的编辑后的问题。 - LazyGuy
1
您可以删除许可证和许可证URL,但请记住,在Swagger 2.0中,许可证名称是必需的。其他配置值可以通过使用代码而不是静态bean来动态完成。请参阅此教程以获取更多信息-https://github.com/swagger-api/swagger-core/wiki/Swagger-Core-JAX-RS-Project-Setup。 - Ron
1
请尝试按照我之前提供的有关BeanConfig的教程。我们的仓库中有一些使用它的样例。除此之外,这与原来的问题无关,我们在这里搞得一团糟。如有其他问题,请使用我们的邮件列表。 - Ron
显示剩余6条评论

15

您可以像这样排除字段:

@ApiModelProperty(position = 1, required = true, hidden=true, notes = "used to display user name")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接