【问题标题】:Using custom JSON format in REST在 REST 中使用自定义 JSON 格式
【发布时间】:2019-04-03 18:04:51
【问题描述】:

我有一个使用 Spring Boot 公开的 REST 服务,该服务使用并生成 JSON。现在我想自定义将从我的服务接受或生成的 JSON 消息,例如我想指定 Accepts: application/x.myCompany.v1+json 而不是 Accepts: application/json。

谁能建议我如何使用 spring 进行此操作?

【问题讨论】:

标签: json spring rest spring-boot


【解决方案1】:

使用以下内容:

@RequestMapping(consumes = "application/x.company.v1+json", 
                produces = "application/x.company.v1+json")

从 Spring 4.2 开始,您可以创建元注释以避免重复自己:

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@RequestMapping(consumes = "application/x.company.v1+json", 
                produces = "application/x.company.v1+json")
public @interface CustomJsonV1RequestMapping {

    @AliasFor(annotation = RequestMapping.class, attribute = "value")
    String[] value() default {};

    @AliasFor(annotation = RequestMapping.class, attribute = "method")
    RequestMethod[] method() default {};

    @AliasFor(annotation = RequestMapping.class, attribute = "params")
    String[] params() default {};

    @AliasFor(annotation = RequestMapping.class, attribute = "headers")
    String[] headers() default {};

    @AliasFor(annotation = RequestMapping.class, attribute = "consumes")
    String[] consumes() default {};

    @AliasFor(annotation = RequestMapping.class, attribute = "produces")
    String[] produces() default {};
}

那么你可以如下使用它:

@CustomJsonV1RequestMapping(method = GET)
public String getFoo() {
    return foo;
}

请参阅此answer 以供参考。

【讨论】:

    【解决方案2】:

    如果您的意思是要为application/x.myCompany.v1+json 定义自定义格式,并且还能够使用application/json 的默认格式提供内容,那么您需要定义一个HttpMessageConverter。这个at baeldung 和另一个logicbig 有一个指南,或者您可以查看registering convertersimplementing the conversion 的示例,以符合一组特定的内容格式指南。

    【讨论】:

      猜你喜欢
      • 2023-03-10
      • 1970-01-01
      • 2021-08-12
      • 1970-01-01
      • 2019-07-05
      • 2021-10-18
      • 2023-03-15
      • 1970-01-01
      • 2017-05-24
      相关资源
      最近更新 更多