1
{"Sam":{"status":"available","classkey":"dotnet"}}

如何解析这种类型的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 对象获取数据。请帮我。

4

2 回答 2

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();
}
于 2013-07-27T09:14:54.620 回答
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();
    }
于 2013-07-27T10:04:47.147 回答