php - 将 JSON 解析为 JSONArray

标签 php android sql json

我的 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 结果都存储在数组的一个索引中 - 所以我希望需要将此方法的返回更改为 JSONArray,对吗?谁能引导我走上正确的道路来解析我从 PHP 脚本收到的 JSON?

最佳答案

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

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

关于php - 将 JSON 解析为 JSONArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10019599/

相关文章:

php - 从 PHP 脚本执行时 MySQL 临时变量不起作用

php - Xdebug 3 不包含在 phpinfo() 中

两个表之间的 MySQL 内部连接

php - FPDF 错误 "Unable to create output file"

php - 如何在 Codeigniter 的迁移库中创建触发器

android - Cordova VS Phonegap 插件

安卓 Kotlin : Mocking a free function using Mockito/PowerMock

android - 如何从 Assets 加载图像?

sql - 如何将 SQL 查询与不同的表达式结合起来?

mysql - 我的 SQL 语句被执行了两次(我是初学者)