2014-09-29 67 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