admin

将JSON解析为JSONArray

sql

我的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?


阅读 45

收藏
2021-06-07

共1个答案

admin

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

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