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

标签 rest cxf jax-rs swagger

我在我的 apache cxf 项目中使用了 swagger,使用了 @Api 和 @ApiOperations 以及 @ApiParam 注释,并为其余服务生成了一个 api 文档。

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

怎么做?

我从 db 获取数据并将其设置为用户对象并将该用户对象传递给 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 格式中的用户对象字段或属性。

我的服务类方法响应是:
    @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 版本,目前是 1.3.12(您使用的是非常旧的版本)。

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

  • 如果您使用 JAXB 注释,您可以使用 @XmlTransient .
  • 如果你使用 Jackson,你可以使用 @JsonIgnore .
  • 如果您不使用其中任何一个,或者不想影响模型的一般反序列化/序列化,您可以使用 Swagger 的 @ApiModelProperty 's hidden attribute .

  • 请记住,您可能需要在您的 getter/setter 上设置这些,而不是在属性本身上。玩弄定义,看看什么对你有用。

    关于 User 模型的问题,问题是您没有从 @ApiOperation 中引用它。 (您也不需要 httpMethod 属性)。尝试如下更改:
    @ApiOperation(value = "xxx", notes = "user details", response =  User.class)
    

    关于rest - 从 Swagger 响应中排除模型或属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27777537/

    相关文章:

    jersey - 在 Jersey StreamingOutput 上调用 flush() 没有效果

    java - 在 Java 客户端、Java 服务器(使用数据库排序)和 Android 手机之间传递图像

    javascript - 适用于所有组合的 JSON faker

    java - Jersey Api 未通过过滤器发送请求

    java - CXF 无 Spring

    java - CXF NoSuchMethodError ClassHelper.getRealClass

    javascript - 使用身份验证登录 frisby 请求 header 中的参数

    java - 使用 CXF 调用 Microsoft CRM 2011 本地 Web 服务

    java - 如何读取 JAX-RS( Jersey )中的 cookie

    Java项目无法引用另一个项目