gpt4 book ai didi

php - 将 JSON 解析为 JSONArray

转载 作者:行者123 更新时间:2023-11-29 02:06:01 27 4
gpt4 key购买 nike

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com