Is it good practice to use @Produces(“application/json”) on all JSON producing endpoints?

前端 未结 2 521
失恋的感觉
失恋的感觉 2021-01-25 07:10

We started using Jersey/JAX-RS for internal REST endpoints that get used by our front-end code. Endpoints that have to return a result, always send JSON objects.

For deb

2条回答
  •  花落未央
    2021-01-25 07:43

    Is it good practice to use @Produces("application/json") on all JSON producing endpoints?

    If your resource methods produce JSON as representation of your resources, they should be annotated with @Produces(MediaType.APPLICATION_JSON). As a result, the response will have a Content-Type header indicating the media type of the payload.

    The @Produces annotation is also used for request matching: The JAX-RS runtime matches the media type sent in the Accept header with the media type defined in the @Produces annotation.


    If you don't want to annotate every resource method in your application, you can annotate the resource classes instead. It will indicate that all methods defined in such class must produce JSON as representation of your resources.


    The media type defined in the @Produces annotation indicates the media type that will be produced by the MessageBodyWriter instances registered in the application. Consider the following example:

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Foo getFoo() {
        Foo foo = new Foo();
        return Response.ok(foo).build();
    }
    

    Once the getFoo() method is annotated with @Produces(MediaType.APPLICATION_JSON), JAX-RS will write the Foo instance as a JSON document. It's done in a MessageBodyWriter implementation. If your application uses Jackson, for example, the JacksonJsonProvider will be used to convert Java objects to JSON documents.

提交回复
热议问题