2015-03-02 25 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);