0

My restful API method looks like this

@GET
@Produces(MediaType.APPLICATION_JSON)
public JSONArray getMessage()
{
    FreeDriversService f=new FreeDriversService();
    try {
      return f.executeFreeDrivers(); // this method return a JSONArray
    } 
    catch(Exception e) {
        System.out.println(e.toString());
        return new JSONArray(); 
    }
} 

When I use the toString() method on JSONArray it does produce a result, but I would like JSON as output. How can i do that?

I am getting this error

A message body writer for Java class org.json.JSONArray, and Java type class org.json.JSONArray, and MIME media type application/json
was not found
David Hoelzer
  • 15,862
  • 4
  • 48
  • 67
Nitin Jaiman
  • 173
  • 1
  • 12

1 Answers1

1

Problem Summary:-

You have mentioned the output as JSON in the @Produces annotation as @Produces(MediaType.APPLICATION_JSON) but instead of sending JSONObject your method getMessage is returning JSONArray. You can not convert a JSON to an JSONArray simply, because in JSONArray same type of JSONObject can be repeated multiple times with same keys, which can be replaced by the later values of the multiple JSONObject.

Solution :-

You can create a JSONObject and can put the JSONArray inside it as a value for a user defined key.

       @GET
        @Produces(MediaType.APPLICATION_JSON)
        public Response getMessage(){
        JSONObject finalJson = new  JSONObject ();
        JSONArray inputArray = new JSONArray();
            FreeDriversService f=new FreeDriversService();
            try{

            inputArray = f.executeFreeDrivers(); // this method return a JSONArray
            }catch(Exception e){
                System.out.println(e.toString());

            }
            finalJson.put("array",inputArray );
            return Response.status(200).entity(finalJson).build();
            }
AnkeyNigam
  • 2,810
  • 4
  • 15
  • 23
  • What should be return type of getMessage? JSONObject as return type is giving same error – Nitin Jaiman Jul 06 '15 at 08:50
  • @NitinJaiman The return type should be `Response` object. From `JSONObject` you can construct `Response` object as `Response.status(200).entity(finalJson).build();` . Edited that in above code as well. – AnkeyNigam Jul 06 '15 at 09:33