【发布时间】:2015-03-02 12:14:07
【问题描述】:
我正在运行 asyncTask 以从 HttpPost 检索 JSON 对象数组。
网络服务的输出是:
[
{
"id": 1,
"question": "What town were you born in?"
},
{
"id": 2,
"question": "What is your mothers maiden name?"
},
{
"id": 3,
"question": "Who was your childhood hero?"
}
]
但是得到JSONException:
org.json.JSONException: End of input at character 0 of
在以下代码中指的是JArray:
JSONArray JArray;
Context ra;
public SecurityQuestionsTask(Context _registerActivity) {
ra = _registerActivity;
JArray = new JSONArray();
}
@Override
protected Long doInBackground(String... langs) {
Long result = 0L;
String lang = Locale.getDefault().getLanguage();
String[] langArray = {"en", "de", "fr"};
if (!Arrays.asList(langArray).contains(lang)) {
lang = "en";
}
try {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://webservice.com/api/v1/securityquestions?lang=" + lang);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
JSONString = EntityUtils.toString(response.getEntity(), "UTF-8");
JArray = new JSONArray(JSONString);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
publishProgress("Retrieving security questions...");
return result;
}
我是否正确地将response 解析为JSONArray?
编辑:
这是 web 服务的响应方式:
return Response.status(200).entity(json.toString()).build();
【问题讨论】:
-
是 EntityUtils.toString(response.getEntity(), "UTF-8");返回预期的 JSON 字符串?它是否分配给传递给 JSONArray 构造函数的变量?
-
共享与
JSONString相同的响应,因为异常说试图将无效字符串转换为 JSONArray 或 JSONObject -
您是否尝试将预期数据输入到
JSONString变量,例如JSONString = "[{\"id\": 1,\"question\": \"What town were you born in?\"}]"?需要诊断您的错误是来自http通信还是内容解析。 -
@Youngjae 我只是这样做了,它并没有从响应中构建
JSONString。 -
网络服务器将
JSONArray转换为String,然后将其作为Response实体发送。这是正确的吗?