{"categories":[{"id":"1","name":"asdf"}]}
Its is my JSON String. i want to get the value of name key .. how can i do it in android ? pleass help
Blockquote
After that you have to get array from JSONObject. Here your get all values from above arrays.
JSONObject object = new JSONObject(yourjsonstring);
JSONArray id = object.getJSONArray("id");
JSONArray name = object.getJSONArray("name");
for(int i=0;i<id.length; i++){
String strid=id.getString(i);
String strname=name.getString(i);
}
Here is your json parsing with exception handling and null checks :
//get json string first from the response and convert it into json object
JSONObject object;
try {
object = new JSONObject("yourjsonstring");
} catch (JSONException e) {
e.printStackTrace();
object = null;
}
JSONArray jsonArray;
if (object != null) {
Object categoryObject = null;
try {
categoryObject = object.get("categories");
} catch (JSONException e) {
e.printStackTrace();
categoryObject = null;
}
if (categoryObject != null) {
if (categoryObject instanceof JSONArray) {
//if categoriew array having more than 1 items
jsonArray = (JSONArray) categoryObject;
} else {
//if categories array having single item
jsonArray = new JSONArray();
jsonArray.put((JSONObject) categoryObject);
}
JSONObject categoryItemObj = null;
for (int i = 0; i < jsonArray.length(); i++) {
try {
categoryObject = jsonArray.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
categoryItemObj = null;
}
if (categoryItemObj != null) {
String id = "";
try {
id = categoryItemObj.getString("id");
} catch (JSONException e) {
e.printStackTrace();
id = "";
}
String name;
try {
name = categoryItemObj.getString("name");
} catch (JSONException e) {
e.printStackTrace();
name = "";
}
}
}
}
}
Or you can use Android's JSONObject. Here's a tutorial - http://www.javacodegeeks.com/2013/10/android-json-tutorial-create-and-parse-json-data.html
public class HttpAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
return GET(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();
try {
JSONObject json = new JSONObject(result);
JSONArray articles = json.getJSONArray("categories");
String name=new String[json.getJSONArray("images").length()]; //initializtion
for(int i=0;i<json.getJSONArray("categories").length();i++){
name[i] = (articles.getJSONObject(i).optString("name"));//here u got your value all name
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
call the asynctask using execute and pass url to it like this
new HttpAsyncTask().execute(url);
from the UI-thread