将JSON解析为JSONArray

时间:2012-04-04 21:35:02

标签: php android sql json

我的PHP成功从我的SQL表中返回JSON。但是我的Android代码将它们全部存储在一个String中。它确实应该存储在一个字符串中,然后解析成多个对象吗?这是相关的代码。

首先,存储的结果当前是什么样的:

04-04 21:26:00.542: V/line(1230): [{"category":"elections","id":"0","title":"Who will you vote for in November's Presidential election?","published":"2012-04-02","enddate":"2012-04-30","responsetype":"0"},{"category":"elections","id":"2","title":"Question title, ladies and gents","published":"2012-04-02","enddate":"2012-04-30","responsetype":"1"}]

所以显然所有的东西都只是作为一个巨大的字符串存储,即使它是两个表行。以下是为我生成该行的代码:

public JSONObject getQuestionJSONFromUrl(String url, List<NameValuePair> params) {

    // Making HTTP request
try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(params));

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

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

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            Log.v("while", line);
            sb.append(line + "\n");
            //Log.v("err", line);
        }
        is.close();
        json = sb.toString();


    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}

显然我现在在WHILE循环后得到各种各样的错误。我花了几天时间尝试解决它,但只是让PHP返回正确的JSON(以前没有)。我希望我需要一个JSONArray,每个JSON结果都存储在Array的一个索引中 - 所以我希望将此方法的返回值更改为JSONArray,这是正确的吗?任何人都可以引导我走正确的路径来解析我从PHP脚本收到的JSON吗?

1 个答案:

答案 0 :(得分:1)

是的,这是正确的。你需要将它解析为JSONArray,因为它就是这样。例如(忽略异常等):

JSONArray jarr = new JSONArray(jsonString);
for (int i = 0; i < jarr.length(); ++i) {
    JSONObject jobj = jarr.getJSONObject(i);
    // work with object
}