【问题标题】: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 以供参考。