2014-09-29 79 views
1

我正在創建一個Http請求來訪問OData服務。我得到了響應,但我不知道如何將響應解析爲一個String對象,以便我可以將它們添加到ArrayList解析Java中的oData響應

這裏是我的代碼:

protected List<StatusResponse> doInBackground(Void... params) 
    { 
     // TODO Auto-generated method stub 
     // Execute HTTP Post Request 

     mResponseList = new ArrayList<StatusResponse>(); 
     HttpClient httpclient = new DefaultHttpClient(); 

     HttpGet httpget = new HttpGet(myOdataQueryUrl); 

     try 
     { 

      HttpResponse responsenext = httpclient.execute(httpget); 
      HttpEntity entitynext = responsenext.getEntity(); 
      AddedResult= EntityUtils.toString(entitynext); 

      jsonArray = new JSONArray(AddedResult); 
      for (int i = 0; i < jsonArray.length(); i++) 
      { 
       JSONObject menuObject = jsonArray.getJSONObject(i); 

       String createdBy = menuObject.getString("CreatedBy"); 
       String comment = menuObject.getString("Comment"); 
       String location = menuObject.getString("Location"); 
       String slot = menuObject.getString("Slot"); 
       String reachingAt = menuObject.getString("StartTime"); 
       String lunch = menuObject.getString("Lunch"); 

       mResponseList.add(new StatusResponse(createdBy, comment, location, slot, reachingAt, lunch)); 
      } 

      } 


     } catch (UnsupportedEncodingException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (ClientProtocolException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 



       return mResponseList; 
    } 

我得到這樣的回答: -

{ 
    "odata.metadata":"mysite/odata/$metadata#OStatus","value":[ 
    { 
     "StatusId":2151,"Location":"Office","Slot":"Running late","StartTime":"2014-09-29T12:30:00","Comment":"-","Lunch":null,"CreatedBy":"","ModifiedBy":null,"Created":"2014-09-29T04:39:10.443","Modified":null 
    } 
    ] 
} 

我碰到下面的錯誤,如果我試圖解析它像上面:

Value {"value":[{"Created":"2014-09-29T04:39:10.443","Modified":null,"StatusId":2151,"ModifiedBy":null,"Slot":"Running late","CreatedBy":"","Comment":"-","Location":"Office","Lunch":null,"StartTime":"2014-09-29T12:30:00"}],"odata.metadata":"https:\/\/mySite\/odata\/$metadata#OStatus"} of type org.json.JSONObject cannot be converted to JSONArray 
+0

看起來像JSON,所以使用JSON解析器。 – nablex 2014-09-29 05:53:32

+0

@nablex請參閱我的編輯代碼和錯誤,我得到 – user2574903 2014-09-29 06:08:37

回答

0

您試圖將普通的JSON對象轉換爲JSON數組。

它似乎也是你聲明該數組是一個字段而不是你的方法的局部變量。你確定這是你需要的嗎?

+0

是的,我只是注意到了這一點。謝謝 – user2574903 2014-09-29 06:25:35