我应该如何使用 jax rs/jersey 从 JSONArray 输出 json?

How should I output json from JSONArray using jax rs/jersey?

我的 restful API 方法如下所示

@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(); 
    }
} 

当我在 JSONArray 上使用 toString() 方法时,它确实产生了结果,但我希望将 JSON 作为输出。我该怎么做?

我遇到这个错误

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

问题总结:-

您在 @Produces 注释中提到 JSON 的输出为 @Produces(MediaType.APPLICATION_JSON) 但您的方法 getMessage 没有发送 JSONObject 而是返回 JSONArray。 您不能简单地将 JSON 转换为 JSONArray,因为在 JSONArray 中,相同类型的 JSONObject 可以使用相同的 keys 重复多次,这可以是替换为 JSONObject.

后面的 values

解决方法 :-

您可以创建一个 JSONObject 并将 JSONArray 作为用户定义的 value 放入其中 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();
            }