2012-02-05 82 views
2

我在這一個的槍下(大約6個小時得到這個工作),我知道我錯過了這裏完全簡單的東西。Android - 解析單個項目響應JSONObject

我想解析一個單一的數據的JSON響應,但我的解析代碼不拾起它。

下面是完整的JSON響應...

{ 「ID」: 「4480」}

的 「4480」 是一個潛在的字母數字數據的反應,所以它可能是像「 A427「。

這是我用來解析單個響應的代碼。問題在於userID爲空 - 它不會在JSON響應中拾取4480。有人可以指出我搞砸了嗎?非常感謝我提前獲得任何幫助!

InputStream is = null; 
       //http post 
       try{ 
        String postQuery = "my api post goes here"; 
        HttpClient httpclient = new DefaultHttpClient(); 
        HttpPost httppost = new HttpPost(postQuery); 
        HttpResponse response = httpclient.execute(httppost); 
        HttpEntity entity = response.getEntity(); 
        is = entity.getContent(); 
       }catch(Exception e){ 
        Log.e("log_tag", "Error in http connection "+e.toString()); 
       } 

       //convert response to string 
       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(); 

       result=sb.toString(); 
       }catch(Exception e){ 
       Log.e("log_tag", "Error converting result "+e.toString()); 
       } 

       //parse json data 
       try { 
       JSONObject userObject = new JSONObject(result); 
       JSONObject jsonid = userObject.getJSONObject("id"); 
       userID = jsonid.getString("id"); 
       } 
+0

什麼是搞砸了?你期望的事情沒有發生?你有例外嗎?如果是這樣,請發佈堆棧跟蹤。 – nhaarman 2012-02-05 13:30:59

+0

userID爲空,所以我的解析代碼實際上並沒有抓取4480 – Rmilligan2372 2012-02-05 13:33:35

+0

因此,如果您嘗試記錄結果字符串,它是否正確檢索數據? – nhaarman 2012-02-05 13:35:26

回答

7

我不是很熟悉JSON解析,但基於this例子,我想你應該改變//parse json data這個:

//parse json data 
try { 
    JSONObject userObject = new JSONObject(result); 
    userID = userObject.getString("id"); 
} catch(Exception ex){ 
    //don't forget this 
} 

也就是說如果調用new JSONObject(result)是正確的。前面提到的例子顯示了這樣的事情:

JSONObject userObject = (JSONObject) JSONSerializer.toJSON(result); 
+0

這樣做!我知道這很簡單,但我只是沒有看到它是什麼。非常感謝你!!! – Rmilligan2372 2012-02-05 13:44:09

+0

NP,有時無偏見的東西真的有幫助:) – nhaarman 2012-02-05 13:48:01

0

試試這個代碼:

try{ 
    final JSONObject jsonObject = new JSONObject(result); 
    if (jsonObject.length() > 0) 
    { 
    String userID = jsonObject.optString("id"); 
    Log.e("TAG", "userID:"+ userID); 
    } 
}catch (Exception e) { 
    e.printStackTrace(); 
} 
+0

@ Rmilligan2372你解決了你的問題嗎? – 2017-01-23 12:22:41