简体   繁体   中英

Sending JSON response with HTTP Status with custom objects

Before you guys point out, I have already tried this solutions

Serialize javax.ws.rs Entity to json

and it didn't work. Here is how I am trying to send the response:

return Response.status(fe.getHttpError())
            .entity(fe)
            .type(MediaType.APPLICATION_JSON)
            .build();

Where fe is an object of type FirstException

public class FlightException extends Exception {
    private int httpError;
    private int errorCode;
    private String message;

    public FirstException(int httpError, int errorCode, String message) {
        this.httpError = httpError;
        this.errorCode = errorCode;
        this.message = message;
    }

    public int getHttpError() {
        return httpError;
    }

    @Override
    public String getMessage() {
        return message;
    }
}

My maven already have following entry

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-json</artifactId>
    <version>1.19</version>
</dependency>

So the question is that how can I send a Response object with HTTP Error code, with custom entity in JSON?

As a side note, if I change this entry to the Glassfish entries from the link I posted earlier, I get following error at startup:

java.lang.AbstractMethodError: javax.ws.rs.core.UriBuilder.uri(Ljava/lang/String;)Ljavax/ws/rs/core/UriBuilder;
    javax.ws.rs.core.UriBuilder.fromUri(UriBuilder.java:119)
    com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:662)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

Generally the status code will be available in the response headers, which i think you already know that. If for some reason you need to send the http status code in the response object, then you have to create an custom Response Wrapper object, which can contain errors as well as response data,

For example, you could do something like,

public class ApiResponse implements Serializable  {

    private List<FirstException> errors;

    private Map<String, Object> data; 
}

then when you can return failure response like

{
"errors": [
  {
  "httpError": 401,
  "errorCode": 401,
  "message": "unauthroized request"
  }
 ]
}

and success response like,

{
"data": {
  "user": {
   "name": "test"
  }
 }
}

this format is also aligned with the standard json api format, checkout http://jsonapi.org/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM