【发布时间】:2013-08-22 11:02:18
【问题描述】:
我是 JSON 新手,不知道 Arraylist 成功转换为 JSONArray 需要遵循的约束。我正在尝试将多个字符串元素的数组列表从 servlet 发送到 JSON 解析器。当我有小元素时同样有效,例如[已解决,正在工作] 但如果数组元素包含空格或特殊字符,我的 JSON Parser 类会引发错误。解析时出现以下错误:
08-20 16:46:13.480: E/JSON Parser(475): Error parsing data org.json.JSONException: Unterminated array at character 17 of [Closed, Emails not working in A-82 premises ; Requested Username: P Smith]
JSON 解析器代码:
public class JSONParser {
static InputStream is = null;
static JSONArray jArr = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONArray getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
//HttpPost httpPost = new HttpPost(url);
HttpGet httpPost = new HttpGet(url);
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) {
sb.append(line + "\n");
}
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 {
jArr = new JSONArray(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jArr;
}
}
【问题讨论】:
-
使用在线 JSON 验证器来验证您的 JSON 并在一切正常时做出响应,之后我们将检查更多错误
-
如何生成数组列表的 JSON 以便我可以通过验证器运行它?
-
在上面的代码中,您正在从 URL 中检索 JSON。这个 JSON 你必须验证
-
使用上面的例子 if array = [Resolved,Working] 然后 JSONArray = ["Resolved","Working"] 这很好。但是如果 array = [Closed, Emails not working] 那么 JSONArray 返回为 null。我没有得到合适的 JSONArray 来通过验证器。
-
在您接触之前验证您直接从您的服务获得的 JSON,以查看 JSON 是否正确。不是 JSON > Android > Array > Json > 验证器。而是执行服务 > JSON > JSON Validator。
标签: android arrays json servlets arraylist