在Java中解析oData响应

时间:2014-09-29 05:23:13

标签: java parsing odata

我正在创建一个访问OData服务的Http请求。我收到了回复,但我不知道如何将响应解析为String对象,以便我可以将它们添加到ArrayList

这是我的代码:

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

1 个答案:

答案 0 :(得分:0)

您正在尝试将普通的JSON对象转换为JSON数组。

您似乎还在声明该数组是一个字段而不是您方法的局部变量。你确定这是你需要的吗?