0

在我的 Android 应用程序中解析此 JSON 数据时遇到问题:

[{"personid":20,"personName":"Ross Gallagher update3","email":"ross_gallagher@rossgallagher.co.uk","birthday":{"date":"2013-01-01 00:00:00","timezone_type":3,"timezone":"America\/Los_Angeles"},"anniversary":{"date":"1900-01-01 00:00:00","timezone_type":3,"timezone":"America\/Los_Angeles"},"Credit":2}]

我得到的错误是:

W/System.err: org.json.JSONException: Value [{"birthday":{"date":"2013-01-01 00:00:00","timezone":"America\/Los_Angeles","timezone_type":3},"anniversary":{"date":"1900-01-01 00:00:00","timezone":"America\/Los_Angeles","timezone_type":3},"email":"ross_gallagher@rossgallagher.co.uk","personName":"Ross Gallagher update8","Credit":2,"personid":20}] of type org.json.JSONArray cannot be converted to JSONObject

我的 JSON 解析器代码是:

public JSONObject getJSONFromUrl(String url)
{
    HttpEntity httpEntity = null;
    JSONObject respObject = null;

    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);

        HttpResponse httpResponse = httpClient.execute(httpGet);
        httpEntity = httpResponse.getEntity();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    if(httpEntity != null){
        try {
            respObject = new JSONObject(EntityUtils.toString(httpEntity));
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //....
    }
    // return JSON
    return respObject;
}

我只需要从这个 JSON 对象中提取生日详细信息以及姓名、电子邮件、信用和周年纪念日。

任何意见,将不胜感激!

4

3 回答 3

1

改变

respObject = new JSONObject(EntityUtils.toString(httpEntity));

respObject = new JSONArray(EntityUtils.toString(httpEntity));

当然 respObject 必须是JSONArray

于 2013-06-07T08:41:24.460 回答
0

The problem is with your JSON String. You need to remove the square brakets [] . Square brakets are used to refer array elements. The JSON parser will try to convert it as array object as json data are inside square braket.

Accept my answer if it helps you.

于 2013-06-07T17:17:17.857 回答
-1

由于您尝试解析的对象实际上是 JSONArray 而不是 JSONObject.. 所以您从该 JSONArray 中获取 JSONObject

JSONArray jsonArray = new JSONArray(EntityUtils.toString(httpEntity));

JSONOject jsonObject = jsonArray.getJSONObject(0);

从这个 jsonObject 你会得到生日的细节......

于 2013-06-07T09:32:45.970 回答