0

我设置了一个 RESTful Web 服务,其中包括以下内容:

    @GET
@Path("{from}/{to}")
@Produces({"application/xml", "application/json"})
public List<Story> findRange(@PathParam("from") Integer from, @PathParam("to") Integer to) {
    return super.findRange(new int[]{from, to});
}

它返回我数据库中所有 Story 对象的列表。我也有这个:

    @GET
@Path("{id}")
@Produces({"application/xml", "application/json"})
public Story find(@PathParam("id") Short id) {
    return super.find(id);
}

当我将“/ {id}”添加到路径的末尾时,它会返回一个 Story 对象。这些都可以在服务器上正常工作,并返回预期的结果。在客户端,后一种方法使用以下代码完美运行:

HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(url);
        httpget.addHeader("accept", "application/json");

        HttpResponse response;
        JSONObject object = new JSONObject();
        String resprint = new String();

        try {
            response = httpclient.execute(httpget);
            // Get the response entity
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                // get entity contents and convert it to string
                InputStream instream = entity.getContent();
                String result= convertStreamToString(instream);
                resprint = result;
                // construct a JSON object with result
                object=new JSONObject(result);
                // Closing the input stream will trigger connection release
                instream.close();
            }
        } 
        catch (ClientProtocolException e) {System.out.println("CPE"); e.printStackTrace();} 
        catch (IOException e) {System.out.println("IOE"); e.printStackTrace();} 
        catch (JSONException e) { System.out.println("JSONe"); e.printStackTrace();}

        System.out.println("FUCKYEAHBG: " + resprint);
        return object;
    }

}

我的问题是,当我尝试将相同的代码与第一个方法一起使用时,它应该返回 JSON Story 对象的列表,我得到一个 JSON 异常:类型不匹配。

如何更改此代码以接受 json 对象数组而不是单个对象?

4

1 回答 1

0

当我问这个问题时想通了: JSONArray 是一种不同类型的对象,独立于 JSONObject,因此 get 请求的结果必须声明为:

            HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(url);
        httpget.addHeader("accept", "application/json");

        HttpResponse response;
        JSONArray object = new JSONArray();
        String resprint = new String();

        try {
            response = httpclient.execute(httpget);
            // Get the response entity
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                // get entity contents and convert it to string
                InputStream instream = entity.getContent();
                String result= convertStreamToString(instream);
                resprint = result;
                // construct a JSON object with result
                object=new JSONArray(result);
                // Closing the input stream will trigger connection release
                instream.close();
            }

想我会完成发布问题,以防任何其他 JSON 菜鸟有这个问题。

于 2013-02-23T23:15:17.837 回答