从Web服务接受一组JSON对象

时间:2013-02-23 23:15:18

标签: java android json

我已经设置了一个包含以下内容的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异常:输入Mismatch。

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

1 个答案:

答案 0 :(得分: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新手有这个问题,我会完成发布问题。