2012-02-05 84 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