从Android中的Response解析Json特定字段

时间:2016-12-24 21:27:21

标签: java android json

{
    "status":"ok",
    "cookie":"dr.steve|akscjn",
    "cookie_name":"wordpress_logged_in",
    "user": {
        "id":330,
        "username":"dr.steve",
        "nicename":"steve",
        "email":"steve@docdirect.com",
        "url":"http:\/\/www.company.com",
        "registered":"2016-12-15 22:21:05",
        "displayname":"Dr.Steve",
        "firstname":"Dr",
        "lastname":"Steve",
        "nickname":"steve",
        "description":"Lorem ipsum",
        "capabilities":"",
        "avatar":null
    }
}

我有这个json响应,我想从这个json中唯一的id字段,我认为有两个嵌套数组,但我发现错误

E /错误:Json解析错误:类型为org.json.JSONObject的用户的值{“id”:330,.........}无法转换为JSONArray

这是我的代码

 if (jsonStr != null) {
                    try {

                        JSONArray ja = new JSONObject(jsonStr).getJSONArray("user");
                        JSONObject c =  ja.getJSONObject(1);
                        String id = c.getString("id");

                        temp2 = id;

                        Log.v("id---->",temp2);

                      }
                    } catch (final JSONException e) {
                        Log.e("Error", "Json parsing error: " + e.getMessage());
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getApplicationContext(),
                                        "Json parsing error: " + e.getMessage(),
                                        Toast.LENGTH_LONG)
                                        .show();
                            }
                        });

                    }
                } else {
                    Log.e("Error", "Couldn't get json from server.");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),
                                    "Couldn't get json from server. Check LogCat for possible errors!",
                                    Toast.LENGTH_LONG)
                                    .show();
                        }
                    });

                }

任何人都可以告诉我在哪里弄错了我将如何从这个json获得id字段?

2 个答案:

答案 0 :(得分:0)

user属性是一个具体对象而不是数组,因此请尝试将其作为对象读取:

JSONObject user = new JSONObject(jsonStr).getJSONObject("user");

答案 1 :(得分:0)

"user":{是一个对象。

数组有方括号。您的数据中没有数组