10

私が構築しようとしているのは、スプリング ブート (v1.2.3) アプリケーションであり、Rest API を SpringFox(swagger2) v2.0.0 で公開します。

私のSwagger Spring構成

@EnableSwagger2
@Configuration
public class SwaggerConfig {

    @Bean
    public Docket myApi() {
        return new Docket(DocumentationType.SWAGGER_2)
            .genericModelSubstitutes(DeferredResult.class)
            .useDefaultResponseMessages(false)
            .forCodeGeneration(false)
            .pathMapping("/my-prj");
    }

}

pojo を json に変換するには gson を使用する必要があり、次のようにします。

@Configuration
public class GsonHttpMessageConverterConfig {

    @Bean
    public GsonHttpMessageConverter gsonHttpMessageConverter(Gson gson) {
        GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
        converter.setGson(gson);
        return converter;
    }
}

問題は、 を使用するGsonHttpMessageConverterと、swagger v2 が間違った json を生成することです。

{
"value": "{\"swagger\":\"2.0\",\"info\":{\"description\":\"Api Documentation\",\"version\":\"1.0\",\"title\":\"Api Documentation\",\"termsOfService\":\"urn:tos\",\"contact\":{\"name\":\"Contact Email\"},\"license\":{\"name\":\"Apache 2.0\",\"url\":\"http:
...

JSON には値のプレフィックスが付けられ、実際の JSON はエスケープされた文字列になります。

を使用しない場合は、次のようになりGsonHttpMessageConverterます。

{
"swagger": "2.0",
"info": {
"description": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a 
...

値とエスケープなしで正しいswagger JSONを作成するソリューションはありますか?

4

5 に答える 5

30

自分で問題を解決しました:

問題は、このクラスのシリアル化にありました:

package springfox.documentation.spring.web.json;

import com.fasterxml.jackson.annotation.JsonRawValue;
import com.fasterxml.jackson.annotation.JsonValue;

public class Json {
  private final String value;

  public Json(String value) {
    this.value = value;
  }

  @JsonValue
  @JsonRawValue
  public String value() {
    return value;
  }
}

正しくシリアル化するために、SpringfoxJsonToGsonAdapter を実装し、gson 構成に追加しました。

アダプタ:

public class SpringfoxJsonToGsonAdapter implements JsonSerializer<Json> {

    @Override
    public JsonElement serialize(Json json, Type type, JsonSerializationContext context) {
        final JsonParser parser = new JsonParser();
        return parser.parse(json.value());
    }
} 

gson 設定:

@Configuration
public class GsonHttpMessageConverterConfig {

    @Bean
    public GsonHttpMessageConverter gsonHttpMessageConverter() {
        GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
        converter.setGson(gson());
        return converter;
    }

    private Gson gson() {
        final GsonBuilder builder = new GsonBuilder();
        builder.registerTypeAdapter(Json.class, new SpringfoxJsonToGsonAdapter());
        return builder.create();
    }
}
于 2015-05-13T16:33:22.980 に答える