1

I have a REST service exposed using Spring Boot that consumes and produces a JSON. Now I want to customize the JSON messages that will be acepted or produced from my service, like instead of Accepts: application/json I want to specify Accepts: application/x.myCompany.v1+json.

Can anyone suggest me how to proceed with this using spring?

Anirban
  • 925
  • 4
  • 24
  • 54

2 Answers2

0

Use the following:

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

Since Spring 4.2, you can create a meta-annotation to avoid repeting yourself:

@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 {};
}

Then you can use it as follows:

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

See this answer for reference.

cassiomolin
  • 124,154
  • 35
  • 280
  • 359
0

If you mean that you want to define a custom format for application/x.myCompany.v1+json and also be able to serve content using default formatting for application/json then you would want to define a HttpMessageConverter. There's a guide on this at baeldung and and another at logicbig or you can see an example of registering converters and implementing the conversion to conform to a specific set of content formatting guidelines.

Ryan Dawson
  • 11,832
  • 5
  • 38
  • 61