【问题标题】:Understand and configure Spring JSON marshalling configuration of String responses了解和配置字符串响应的 Spring JSON 编组配置
【发布时间】:2021-06-16 21:31:34
【问题描述】:

对于 Spring MVC 项目(不是 Spring Boot),我正在配置 JSON 转换器以自定义所有 REST 端点的 JSON 响应,即删除 null 字段并设置日期格式。将 SpringDoc 引入项目后,我必须添加一个 StringHttpMessageConverter 以防止生成的 OpenAPI JSON 作为字符串返回。

没有StringHttpMessageConverter,OpenAPI JSON 看起来像这样:

"{\"openapi\":\"3.0.1\",\"info\":{\"title\":\"OpenAPI definition\",\"version\":\"v0\"},\"servers\":[{\"url\":\"http://localhost:8080\",\"description\":\"Generated server url\"}],\"paths\":{\"/get\":{\"get\":{\"tags\":[\"controller\"],\"operationId\":\"getSomeMap\",\"responses\":{\"200\":{\"description\":\"default response\",\"content\":{\"*/*\":{\"schema\":{\"$ref\":\"#/components/schemas/ImmutableMultimapStringString\"}}}}}}}},\"components\":{\"schemas\":{\"ImmutableMultimapStringString\":{\"type\":\"object\",\"properties\":{\"empty\":{\"type\":\"boolean\"}}}}}}"

使用StringHttpMessageConverter,它看起来像这样,这是期望的结果:

{"openapi":"3.0.1","info":{"title":"OpenAPI definition","version":"v0"},"servers":[{"url":"http://localhost:8080","description":"Generated server url"}],"paths":{"/get":{"get":{"tags":["controller"],"operationId":"getSomeMap","responses":{"200":{"description":"default response","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ImmutableMultimapStringString"}}}}}}}},"components":{"schemas":{"ImmutableMultimapStringString":{"type":"object","properties":{"empty":{"type":"boolean"}}}}}}

然而,这确实会导致多个端点返回字符串作为响应的问题。他们应该返回一个有效的 JSON 字符串:"response-string",但他们将字符串作为纯文本返回:response-string,省略双引号,使其无效。

如何保持当前配置不变,以便正确返回 SpringDoc OpenAPI JSON,同时让具有字符串响应的端点返回有效的 JSON 字符串?

使用的配置:

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    WebContentInterceptor webContentInterceptor = new WebContentInterceptor();
    webContentInterceptor.setCacheSeconds(0);
    webContentInterceptor.setUseExpiresHeader(true);
    webContentInterceptor.setUseCacheControlHeader(true);
    webContentInterceptor.setUseCacheControlNoStore(true);
    registry.addInterceptor(webContentInterceptor);
  }

  @Override
  public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
    Map<String, MediaType> mediaTypes = new HashMap<>();
    mediaTypes.put("json", MediaType.APPLICATION_JSON);
    mediaTypes.put("xml", MediaType.APPLICATION_XML);

    configurer.favorPathExtension(false);
    configurer.favorParameter(true);
    configurer.mediaTypes(mediaTypes);
    configurer.defaultContentType(MediaType.APPLICATION_JSON_UTF8);
  }

  @Override
  public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
    configurer.enable();
  }

  @Override
  public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    // Note that the order matters here! If the StringHttpMessageConverter is add after the jsonConverter
    // the documentation JSON is returned as a giant string instead of a (valid) JSON object
    converters.add(new StringHttpMessageConverter());
    converters.add(jsonConverter());
  }

  @Bean
  public MappingJackson2HttpMessageConverter jsonConverter() {
    List<MediaType> supportedMediaTypes = new ArrayList<>();
    supportedMediaTypes.add(MediaType.APPLICATION_JSON);

    Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
    builder.serializationInclusion(JsonInclude.Include.NON_NULL);
    builder.timeZone(TimeZone.getTimeZone(timeZone));

    MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter(
        builder.build()
    );
    jsonConverter.setSupportedMediaTypes(supportedMediaTypes);
    return jsonConverter;
  }

  @Bean
  public Jaxb2Marshaller jaxb2Marshaller() {
    Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller();
    jaxb2Marshaller.setClassesToBeBound(KioskProfiel.class, KioskProfielRegel.class, TitlesetTO.class, TitlesetTitel.class);

    return jaxb2Marshaller;
  }

  @Bean
  public MarshallingHttpMessageConverter marshallingConverter() {
    List<MediaType> supportedMediaTypes = new ArrayList<>();
    supportedMediaTypes.add(MediaType.APPLICATION_XML);

    MarshallingHttpMessageConverter marshallingConverter = new MarshallingHttpMessageConverter(jaxb2Marshaller());
    marshallingConverter.setSupportedMediaTypes(supportedMediaTypes);
    return marshallingConverter;
  }
}

编辑

我尝试覆盖OpenApiResource,将端点的produces 值设置为TEXT_PLAIN_VALUE 和application/json,但问题仍然存在。不允许尝试将返回类型从 String 更改为 TextNode,因此这似乎不是一个选项。 或者,我尝试通过注册 Filter 来更正格式错误的响应来解决问题,但这不起作用。

也许我仍然缺少一些东西,但我别无选择。使用我当前的项目配置,当使用自定义 MappingJackson2HttpMessageConverter 时,我无法让 SpringDoc 返回有效的 OpenAPI JSON。现在我会坚持使用 Swagger 2.0,并会寻找一个替代库来迁移到 OpenAPI 3.0。

【问题讨论】:

  • 你不能同时拥有它。使用 String 返回类型/值和注册的 StringHttpMessageConverter(在第 0 位),总是将 String 的内容写入响应。如果在一个调用站点中,您希望将该内容解释为 JSON 字符串,您可以将其包装并返回到 Jackson TextNode。
  • 为了得到我想要的结果,字符串作为有效的 JSON 并且 OpenAPI JSON 不作为字符串返回,这意味着删除 StringHttpMessageConverter 并找到另一种方法来防止 OpenAPI JSON 被转换到一个字符串?我真的不明白为什么 OpenAPI JSON 作为字符串而不是 JSON 对象返回,这使得很难查明原因并找到可能的解决方案。
  • 您可以自己将 OpenAPI JSON 作为TextNode 返回。并放弃StringHttpMessageConverter。
  • 将 JSON 作为TextNode 返回会将其保留为 JSON 而不是将其转换为(转义的)字符串?我怎样才能做到这一点?我试图覆盖OpenApiResource 提到的here 但是我没有让它工作。很多用过的类都找不到了。
  • 对不起,我不熟悉这个 API。但根据你所说的,你有类似String json = SomeOpenAPI.get(); 的东西。然后,您可以只使用return TextNode.valueOf(json);,Jackson 将负责“序列化”它。

标签: java json spring-mvc springdoc-openapi-ui


【解决方案1】:

终于找到了可行的解决方案!它由两部分组成。首先是配置转换器。简而言之,我们注册了默认转换,之后默认的 JSON 转换器 MappingJackson2HttpMessageConverter 被删除,我们的自定义 JSON 转换器作为第一个转换器添加到转换器列表中。重要的是,自定义 JSON 转换器位于转换器列表中 StringHttpMessageConverter 之前的转换器列表中,否则返回 JSON 且其 Java 返回类型为 String 的端点返回不带双引号的字符串,使其无效 JSON。

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

  @Override
  public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
    converters.removeIf(converter -> converter instanceof MappingJackson2HttpMessageConverter);
    converters.add(0, jsonConverter());
  }

  @Bean
  public MappingJackson2HttpMessageConverter jsonConverter() {
    List<MediaType> supportedMediaTypes = new ArrayList<>();
    supportedMediaTypes.add(MediaType.APPLICATION_JSON);

    Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
    builder.serializationInclusion(JsonInclude.Include.NON_NULL);
    builder.timeZone(TimeZone.getTimeZone(timeZone));

    MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter(
        builder.build()
    );
    jsonConverter.setSupportedMediaTypes(supportedMediaTypes);
    return jsonConverter;
  }

}

其次,这会导致 OpenAPI JSON 成为一个大(转义)字符串,如问题中所述。为了解决这个问题,我们覆盖了OpenApiWebMvcResource 类中的openapiJson 方法(和端点),它默认用于返回OpenAPI JSON,以生成text/plain 而不是application/json。这样,文档 JSON 就不再作为(转义的)字符串返回。

@RestController
public class OpenApiResource extends OpenApiWebMvcResource {

  @Override
  @Operation(hidden = true)
  @GetMapping(value = Constants.API_DOCS_URL, produces = MediaType.TEXT_PLAIN_VALUE)
  public String openapiJson(
    HttpServletRequest request,
    @Value(Constants.API_DOCS_URL) String apiDocsUrl
  )
    throws JsonProcessingException {
    calculateServerUrl(request, apiDocsUrl);
    OpenAPI openAPI = this.getOpenApi();
    return Json.mapper().writeValueAsString(openAPI);
  }

}

请注意,为简洁起见,上述两个示例类中仅列出了相关方法。

【讨论】:

    猜你喜欢
    • 2019-05-22
    • 2016-04-21
    • 2021-04-12
    • 2014-09-04
    • 1970-01-01
    • 1970-01-01
    • 2014-09-02
    • 2014-12-29
    • 1970-01-01
    相关资源
    最近更新 更多