我正在尝试将一些 JSON 解析为 Android 中的单独对象。对象由一个结束大括号分隔,没有空格,然后是一个开始大括号(“第一个结束 {第二个开始”)。到目前为止,我的代码允许我找到这些点在 JSON 中的位置,但我不知道使用什么方法来拆分对象然后存储它们。这是我获取 JSON 然后尝试解析的代码:
public ArrayList<String> 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 {
ArrayList<String> questionsList = new ArrayList<String>();
int count = 0;
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
String newLine = null;
String newLine2 = null;
int previousJ = 0;
if ((line = reader.readLine()) != null) {
for(int j = 0; j < line.length(); j++) {
while (line.charAt(j) == '}' && line.charAt(j+1) == '{') {
//everything before j = 1 string
//everything after gets deleted because I can't think
//of anything better, yet
sb.append(line);
sb.delete(j+1, sb.length());
line = sb.toString();
questionsList.add(count, line);
//line = line.split("\\}\\{");
Log.v("forintbs", questionsList.toString());
count++;
}
}
}
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 null;
}
显然,该方法现在返回 null,因为无论如何它都无关紧要。到目前为止,当我查看日志以查看打印输出时,我的数组列表是一长并且已按预期正确获取字符串 - 但原始数据的其余部分也按预期删除。我已经完全按照原样保留了我的代码,因此您可以看到我尝试过的内容。有没有人有什么建议?以下是一些示例 JSON:
{"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"}
我不使用 ArrayList 没有问题,而是使用 JSON 对象数组。我只是按照我昨天提出的问题中的建议进行尝试。
编辑~ 这是我的 PHP 脚本:
<?php
define("DB_HOST", "localhost");
define("DB_USER", "*");
define("DB_PASSWORD", "*");
define("DB_DATABASE", "*");
mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
mysql_select_db(DB_DATABASE);
$sql=mysql_query("select * from QUESTIONS where CATEGORY like 'elections'");
while($row=mysql_fetch_assoc($sql)) {
$output[]=$row;
}
foreach($output as $value) {
echo json_encode($value);
}
?>