如何从Android中的JSON响应中获取特定价值?

Man*_*ano -2 android android-json

我想"result"从下面的JSON响应中获取值并将其存储在本地.这是代码:

private class GetContacts extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... arg0) {
            // Creating service handler class instance
            ServiceHandler sh = new ServiceHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

            if (jsonStr != null) {
                    try {
                        JSONObject jsonObj = new JSONObject(jsonStr);

                        //JSONArray contacts;
                        contacts = jsonObj.getJSONArray("response");
                        Log.d("Response: ", "> " + contacts);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    Log.e("ServiceHandler", "Couldn't get any data from the url");
                }
                return null;
        }
    }
Run Code Online (Sandbox Code Playgroud)

我的回复 :

{"response":

        [{
            "name":"ajay",
            "class":"7",
        },

        {
            "rank":1
        }],


        "date":

        {
            "startdate":2/12/2012,
        },
            "result":"pass"
        }
Run Code Online (Sandbox Code Playgroud)

Mys*_*icϡ 5

您需要从json String创建一个JSON对象,然后获取并检索其数据:

JSONObject json= new JSONObject(responseString);  //your response
try {
    String result = json.getString("result");    //result is key for which you need to retrieve data
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你.