Search code examples
jersey-2.0

How should I return JSON response in Jersey 2


I'm facing issue while trying to return Response with JSON object in Jersey 2.

Following is the code snippet:

        import javax.ws.rs.GET;
        import javax.ws.rs.Path;
        import javax.ws.rs.Produces;
        import javax.ws.rs.core.MediaType;
        import javax.ws.rs.core.Response;
        import javax.ws.rs.core.Response.Status;
        import org.codehaus.jettison.json.JSONObject;

        @Path("/message")
        public class HelloWorld {

          @Path("/getJson")
          @GET
          @Produces(MediaType.APPLICATION_JSON)
          public Response getJSON() {
            JSONObject object = null;
            Response response = null;
            try {
              object = new JSONObject();
              object.put("Name", "Bryan");
              object.put("Age", "27");
              response = Response.status(Status.OK).entity(object).build();
            } catch (Exception e) {
              System.out.println("error=" + e.getMessage());
            }
            return response;
          }
        }

I'm getting the below exception:

 No serializer found for class org.codehaus.jettison.json.JSONObject and no  properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS)

Related posts advised me to try the following.

  1. Use ObjectMapper and set the property mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); : I don't need to use ObjectMapper in this scenario as I just want to return a json object.

  2. Try POJO instead of JSON Object: Yes POJO works fine but that is not what I wanted. I need to return the Response with Json object which will be parsed by my Java script code.


Solution

  • Get the String from JSONObject and set that String in Response. Something like below -

     object = new JSONObject();
     object.put("Name", "Bryan");
     object.put("Age", "27");
     response = Response.status(Status.OK).entity(object.toString()).build();