2

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

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

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 吗?

4

1 回答 1

1

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

JSONArray jarr = new JSONArray(jsonString);
for (int i = 0; i < jarr.length(); ++i) {
    JSONObject jobj = jarr.getJSONObject(i);
    // work with object
}
于 2012-04-04T21:39:02.110 回答