Java 从GET请求接收空JSON数组
我正在运行一个Java 从GET请求接收空JSON数组,java,android,json,object,Java,Android,Json,Object,我正在运行一个asyncTask,从HttpPost检索对象的JSON数组 webservice的输出为: [ { "id": 1, "question": "What town were you born in?" }, { "id": 2, "question": "What is your mothers maiden name?" }, { "id": 3,
asyncTask
,从HttpPost
检索对象的JSON数组
webservice的输出为:
[
{
"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;
}
我是否正确解析了对JSONArray
的响应
编辑:
以下是Web服务的响应方式:
return Response.status(200).entity(json.toString()).build();
如果字符串
响应与您发布的类似,请尝试
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
String resp = EntityUtils.toString(response.getEntity(), "UTF-8");
JSONArray jsonArr = new JSONArray(resp);
线索似乎就在问题的标题里
我不得不使用HttpGet
而不是HttpPost
来设置我的web服务
所以这一行:
HttpPost httppost = new HttpPost("http://webservice.com/api/v1/securityquestions?lang=" + lang);
必须改变这一点:
HttpGet httpGet = new HttpGet("http://webservice.com/api/v1/securityquestions?lang=" + lang);
是EntityUtils.toString(response.getEntity(),“UTF-8”);返回所需的JSON字符串?它被分配给传递给JSONArray构造函数的变量了吗?共享进入JSONString
的相同响应,因为尝试将无效字符串转换为JSONArray或JSONObject时出现异常,您是否尝试将预期数据输入JSONString
变量,如JSONString=“[{\'id\”:1,\'question\:\”你出生在哪个城镇?\“}]”
?需要诊断您的错误是来自http通信还是内容解析。@Youngjae我刚刚做了这件事,它不是从响应中构建JSONString
。Web服务器将JSONArray
转换为字符串,然后将其作为响应
实体发送。这是正确的吗?我需要JSONArray成为类对象,这样我就可以使用它来填充AsycTask
的onPostExecute
方法中的列表JSONArray
可以成为对象成员,没问题,只需删除前面的声明JSONArray
,然后像您实际做的那样在类中声明jsonArr
。