How to return Array of two JSON Object in Jersey RESTFul API(JAX-RS)

722 views Asked by At

I have designed login module in RESTFul API using jersey.

whenever any error occurred while login it will return error code and message like,

{
  "errorFlag": 1,
  "errorMessage": "Login Failed"
} 

but whenever I get successful results it returns

{
  "apiKey": "3942328b-fa65-496c-bf32-910aafbc1b0e",
  "email": "[email protected]",
  "name": "Chandrakant"
}

I'm looking for results like below

    {
          "errorFlag": 0,
          "errorMessage":{
          "apiKey": "3942328b-fa65-496c-bf32-910aafbc1b0e",
          "email": "[email protected]",
          "name": "Chandrakant"}
 }
2

There are 2 answers

2
Kiran Kumar On

Use structure like below,

{
  status/statusCode :  200/400, //eg. 200 for success, any other for failure.
  statusMessage : "Success/<failureMessage>",
  errorDetails : "Failed due to <reason>"   //optional
  data :{    //data will exists only in case of success call.
  }
}

you can achieve this like below,

@GET
@Path("/images/{image}")
@Produces("image/*")
public Response getImage(@PathParam("image") String image) {
  File f = new File(image);
 
  if (!f.exists()) {
    throw new WebApplicationException(404);
  }
 
  String mt = new MimetypesFileTypeMap().getContentType(f);
  return Response.ok(f, mt).build();
}
0
Lokesh On

You can return all the attributes in HashMap as key value . Below piece of code worked for me

@POST @Path("/test") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public HashMap check(InputStream inputJsonObj) { HashMap map = new HashMap(); map.put("key1", "value1"); return map;
}