2013-07-27 48 views
1
{"Sam":{"status":"available","classkey":"dotnet"}} 

如何解析此類型的json?Android JSON對象解析,無法獲取狀態

try { 
       JSONObject jObj = new JSONObject(json); 
       if(jObj != null){ 
        domtdl = jObj.getString(dom); 
        try { 
         JSONObject c = new JSONObject(domtdl); 
         if(c != null){ 
          status = c.getString(TAG_STATUS); 
          System.out.println(status); 
         } 
        } catch (JSONException e) { 
         e.printStackTrace(); 
        } 
       }   

      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 

它正確嗎? 我不知道如何從第二個JSON對象獲取數據。 請幫幫我。

回答

1

對於這個特定的JSON字符串{"Sam":{"status":"available","classkey":"dotnet"}}

你需要做的

try { 
    JSONObject jObj = (new JSONObject(json)).getJSONObject("Sam"); 
    String status = jObj.getString("status"); 
    String classkey = jObj.getString("classkey"); 
} catch (JSONException e) { 
    e.printStackTrace(); 
} 
0
 try 
     { 
     JSONObject jb = new JSONObject(myjsonstring); 
     JSONObject job = jb.getJSONOBject("Sam"); 
     String status = job.getString("status"); 
     Log.i("Status is",status); 
     String classkey = job.getString("classkey"); 
     Log.i("Class Key is",classkey); 
     catch (JSONException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
     } 

{代表一個JSON對象節點

{ // json object node 
"Sam": { // json object SAM 
    "status": "available", json string 
    "classkey": "dotnet" json string 
} 
} 

JSON教程@

http://www.w3schools.com/json/

你的json有時也可能看起來像下圖。

[表示JSON數組節點

{ 
"employees": [ 
    { 
     "firstName": "John", 
     "lastName": "Doe" 
    }, 
    { 
     "firstName": "Anna", 
     "lastName": "Smith" 
    }, 
    { 
     "firstName": "Peter", 
     "lastName": "Jones" 
    } 
] 
} 

爲了解析上述

StringBuilder sb = new StringBuilder(); 
     try { 
     JSONObject jb = new JSONObject(myjsonstring); 
     JSONArray jarr = jb.getJSONArray("employees"); 
     for(int i=0;i<jarr.length();i++) 
     { 
      JSONObject job = jarr.getJSONObject(i); 
      String firstname = job.getString("firstName"); 
      String lastname = job.getString("lastName"); 
      sb.append(firstname); 
      Log.i("firstname",firstname); 
      sb.append("\n"); 
      Log.i("lastname",lastname); 
     } 
     Toast.makeText(getApplicationContext(), sb, 10000).show(); 
    } catch (JSONException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    }