Skip to content

JAX-RS — How to return JSON and HTTP status code together?

In JAX-RS, you can use the Response class from the jakarta.ws.rs.core package to return a JSON response and an HTTP status code together. Here's an example of how to do this:


java
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;

@Path("/example")
public class ExampleResource {

  @GET
  public Response getExample() {
    Object obj = // create your JSON object here
    return Response.status(200).entity(obj).type(MediaType.APPLICATION_JSON).build();
  }

}

This will return a JSON response with an HTTP status code of 200 OK.

You can also use the Response class to return other HTTP status codes. For example, to return a 404 Not Found response, you can use the following code:


java
return Response.status(404).build();

This will return an empty response with an HTTP status code of 404 Not Found.

Note: For automatic JSON serialization to work, a JSON provider like Jackson or Moxy must be on the classpath. You can find a list of HTTP status codes and their meanings in the HTTP specification.

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.