swagger JSON文件的空值

时间:2015-12-02 14:33:14

标签: java rest jersey jackson swagger

我在使用Java注释生成的JSON swagger文档时遇到了一些麻烦(REST使用Jersey公开,序列化由jackson处理)。查看生成的swagger,它包含空值,这会导致swagger UI崩溃(生成的YAML没有此问题)。

这是JSON的摘录:

{
  "swagger": "2.0",
  "info": { "description": null, "version": "1.0.0", "title": "", "termsOfService": null, "contact": null, "license": null },
  "host": "localhost:8080",
  "basePath": "/api",
  "tags": [ { "name": "dataset", "description": null, "externalDocs": null } ],
  "schemes": [ "http" ],
  "consumes": null,
  "produces": null,
  "paths": {
    "/dataset": {
      "get": {
        "tags": ["dataset"],
        "summary": "A dataset",
        "description": "All the available datasets",
        "operationId": "datasetGet",
        "schemes": null,
        "consumes": null,
        "produces": ["application/json"],
        "parameters": [],
        "responses": {
          "200": {
            "description": "Available datasets",
            "schema": {
              "type": "object",
              "format": null,
              "example": null,
              "xml": null,
              "position": null,
              "description": null,
              "title": null,
              "readOnly": null,
              "additionalProperties": {
                "type": "object",
                "format": null,
                "example": null,
                "xml": null,
                "position": null,
                "description": null,
                "title": null,
                "readOnly": null,
                "additionalProperties": {
                  "type": "object",
                  "format": null,
                  "example": null,
                  "xml": null,
                  "position": null,
                  "description": null,
                  "title": null,
                  "readOnly": null,
                  "properties": null
                }
              }
            },
            "examples": null,
            "headers": null
          }
        },
        "security": null,
        "externalDocs": null,
        "deprecated": null
      },
      "head": null,
      "post": null,
      "put": null,
      "delete": null,
      "options": null,
      "patch": null,
      "parameters": null
    }
  },
  "parameters": null,
  "responses": null,
  "externalDocs": null,
  "securityRequirement": null
}

This solution建议设置对象映射器以省略空值来解决问题,但现实是我不知道在何处或如何轻松访问映射器,并在REST服务上使用NON_NULL注释上课没有意义。类似的问题has been asked也是如此,但我不使用Spring(所以我没有地方设置自定义映射器或设置它)。

我过去使用的是Swagger,但配置设置不同(与wink结合使用,现在我使用的是平针织物)并且没有这个问题。

如果有一些明显的错误配置,这是我的web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">

    <display-name>MyProject</display-name>

    <!-- Rest services mapping -->
    <servlet>
        <servlet-name>jersey</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
        <param-name>jersey.config.server.provider.classnames</param-name>
        <param-value>
            io.swagger.jersey.listing.ApiListingResourceJSON,
            org.something.DatasetApi
        </param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>jersey</servlet-name>
        <url-pattern>/service/*</url-pattern>
    </servlet-mapping>

    <!-- Swagger config class -->
    <servlet>
        <servlet-name>DefaultJaxrsConfig</servlet-name>
        <servlet-class>io.swagger.jaxrs.config.DefaultJaxrsConfig</servlet-class>
        <init-param>
            <param-name>api.version</param-name>
            <param-value>1.0.0</param-value>
        </init-param>
        <init-param>
            <param-name>swagger.api.basepath</param-name>
            <param-value>http://localhost:8080/api</param-value>
        </init-param>
        <load-on-startup>2</load-on-startup>
    </servlet>

    <!-- Just the CORS filter -->
    <filter>
        <filter-name>ApiOriginFilter</filter-name>
        <filter-class>org.something.ApiOriginFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>ApiOriginFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

这是我的pom.xml(我总是对swagger依赖关系感到困惑):

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <groupId>org.something</groupId>
    <artifactId>my_project</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <modelVersion>4.0.0</modelVersion>
    <packaging>war</packaging>
    <name>My Project</name>
    <url>http://maven.apache.org</url>

    <build><finalName>MyProject</finalName></build>

    <properties>
        <maven.compiler.source>1.6</maven.compiler.source>
        <maven.compiler.target>1.6</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.0.13</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.1</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <!-- if your container implements Servlet API older than 3.0, use "jersey-container-servlet-core" -->
            <artifactId>jersey-container-servlet</artifactId>
            <version>2.6</version>
        </dependency>
        <!-- Required only when you are using JAX-RS Client -->
        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-client</artifactId>
            <version>2.6</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <!-- scope>provided</scope -->
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.jaxrs</groupId>
            <artifactId>jackson-jaxrs-json-provider</artifactId>
            <version>2.4.2</version>
        </dependency>

        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-jersey2-jaxrs</artifactId>
            <version>1.5.4</version>
        </dependency>

    </dependencies>


</project>

最后,为了完整性,这是我的Java类的摘录:

package org.something;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

import java.util.Map;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Path("/dataset")
@Produces({ "application/json" })
@Api(value = "/dataset", description = "the dataset API")
public class DatasetApi  {

    private static final Logger log = LoggerFactory.getLogger(DatasetApi.class);

    @GET
    @ApiOperation(value = "All the available datasets.", notes = "Available datasets", response = Map.class, responseContainer = "Map")
    @ApiResponses(value = { @ApiResponse(code = 200, message = "Map of the available datasets", response = Map.class, responseContainer = "Map") })
    public Map<String, String> datasetGet() {
        try {
            log.info("Returning list of dataset");
            return Storage.datasets().getDatasets();
        } catch(Exception e) {
            log.info("Exception!", e);
            throw new WebJsonException(e, Response.Status.INTERNAL_SERVER_ERROR);
        }
    }

}

理想情况下,我想要一个以前调用过的类或者包含swagger逻辑的类(通过在web.xml中声明它)并做一个简单的mapper.setSerializationInclusion(Include.NON_NULL);来解决所有麻烦,但我不喜欢不知道是否以及如何做到这一点。

2 个答案:

答案 0 :(得分:7)

我已经花了一个星期的时间,我在发布问题后几个小时就找到了解决方案,对不起。

似乎在web.xml中缺少ServletContainer中的io.swagger.jaxrs.listing.SwaggerSerializers类,完整部分是:

<servlet>
    <servlet-name>jersey</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
    <param-name>jersey.config.server.provider.classnames</param-name>
    <param-value>
        io.swagger.jersey.listing.ApiListingResourceJSON,
        io.swagger.jaxrs.listing.SwaggerSerializers,
        org.something.DatasetApi
    </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

使用io.swagger.jaxrs.listing.SwaggerSerializers位,所有内容现在都按预期工作。

答案 1 :(得分:3)

如果使用spring-boot,您可以在application.yml中设置:

spring.jackson.default-property-inclusion: non_null