2013-02-23 91 views
0

我已經建立包括以下內容的RESTful Web服務接受JSON對象的數組:從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}); 
} 

返回我的數據庫中的所有故事對象的列表。我也有:

@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對象而不是單個數組?

回答

0

想通了當我提出質疑:甲JSONArray是一個明顯的類型的對象,獨立的JSONObject的,並且因此獲取請求的結果必須被聲明爲這樣:

  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 noob有這個問題,我會發布這個問題。