2015-03-02 123 views
0

我正在运行asyncTask以从HttpPost中检索JSON数组对象。从GET请求接收空的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; 
} 

我是解析responseJSONArray相关ctly?

编辑:

这是Web服务的响应:

return Response.status(200).entity(json.toString()).build(); 
+3

是EntityUtils.toString(response.getEntity(), “UTF-8”);返回预期的JSON字符串?它被分配给一个传递给JSONArray构造函数的变量吗? – nomis 2015-03-02 12:18:34

+1

分享同样的反应,得到'JSONString',因为异常说试图将无效字符串转换为JSONArray或JSONObject – 2015-03-02 12:20:11

+1

您是否尝试输入预期的数据到'JSONString'变量如'JSONString =“[{\”id \“:1 ,“问题”:“你出生在哪个城镇?”)“'?它需要诊断您的错误是来自http通信还是内容解析。 – Youngjae 2015-03-02 12:26:53

回答

-1

如果String反应就像是你贴的人,尝试

 // Execute HTTP Post Request 
    HttpResponse response = httpclient.execute(httppost); 
    String resp = EntityUtils.toString(response.getEntity(), "UTF-8"); 
    JSONArray jsonArr = new JSONArray(resp); 
+0

我需要JSONArray作为类对象,所以我可以用它来填充'AsycTask'的'onPostExecute'方法中的列表。 – crm 2015-03-02 12:55:21

+0

'jsonArray'可以是一个对象成员,没问题,只要在前面删除声明'JSONArray'并像你实际那样在类中声明'jsonArr'。 – 2015-03-02 13:11:10

0

线索是在问题的标题它似乎!

我不得不使用HttpGet而不是HttpPost与我的网络服务设置的方式。

所以这行:

HttpPost httppost = new HttpPost("http://webservice.com/api/v1/securityquestions?lang=" + lang); 

不得不改变到这样的:

HttpGet httpGet = new HttpGet("http://webservice.com/api/v1/securityquestions?lang=" + lang);