我希望从以下JSON响应中获取"result"
的值并将其存储在本地。以下是代码:
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;
}
}
我的回复:
{"response":
[{
"name":"ajay",
"class":"7",
},
{
"rank":1
}],
"date":
{
"startdate":2/12/2012,
},
"result":"pass"
}
答案 0 :(得分: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();
}
希望它有所帮助。
答案 1 :(得分:4)
请提供正确且完整的JSON响应。所以我可以告诉你解析JSON的方法:
String jsonStr; // hold your JSON response in String
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// If you have array
JSONArray resultArray = jsonObj.getJSONArray("response"); // Here you will get the Array
// Iterate the loop
for (int i = 0; i < resultArray.length(); i++) {
// get value with the NODE key
JSONObject obj = resultArray.getJSONObject(i);
String name = obj.getString("name");
}
// If you have object
String result = json.getString("result");
} catch (Exception e) {
e.printStackTrace();
}
答案 2 :(得分:0)
试试这个......
@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 json= new JSONObject(jsonStr); //your json response
String result = json.getString("result"); //result data
} catch (JSONException e) {
e.printStackTrace();
}
}
}