I\'m parsing this url and I\'ve got an exception and don\'t know how to skip it over... I need to get only names of 100 the most popular apps. There is key \"im:name\" and i
You are not accessing the values the right way, check this:
JsonParser jParser = new JsonParser();
JSONObject json = jParser.getJSONFromUrl(jsonStringUrl);
JSONObject feeds = json.getJSONObject("feed");
dataJsonArr = feeds.getJSONArray("entry");
for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(i);
String name = c.getString("im:name");
Log.d("mylog", "name = " + name);
}
You probably want to append this data into an array list, otherwise you would be overwriting these variables.
Please note org.json is a limited library i have personally experienced its limitation when the json data is too large.
I suggest you to ditch it and use GSON or jackson which are fare more advanced.
Thanks to njzk2 for the advice to avoid using JSONParser
, so I've made all I needed in very shorter time and with less efforts.
I needed to get root JSONObject
- names of applications in iTunes.
and insert it into database.
This is the full code of the method doInBackground
in AsyncTask.class
@Override
protected Boolean doInBackground(Void... params) {
Log.d(LOG, "AsyncTask. Do in background");
ContentValues cv = new ContentValues();
try {//Making a request to server getting entities
JSONObject json = new JSONObject(EntityUtils.toString(
new DefaultHttpClient().execute(
new HttpGet(url)).getEntity()));
//getting json root object
JSONObject feedObject = json.getJSONObject("feed");
//getting needed array in root json object
JSONArray entryArray = feedObject.getJSONArray("entry");
//moving though the array
for(int i = 0; i < entryArray.length(); i++){
//getting all objects in array
JSONObject entryObjects = entryArray.getJSONObject(i);
//taking objects with needed key
JSONObject nameObject = entryObjects.getJSONObject("im:name");
//getting string name
String name = nameObject.getString("label");
//putting data into ContentValues - name and id (for making a numbers
// next to records in ListView)
cv.put(DB.COL_NAME, name);
cv.put(DB.COL_ID, i+1);
mDB.insert(cv);
//just controlling in log
Log.d(LOG, "" + name);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
First You make a call get the result into a string called json. Then You have to convert the string into Json object
String json = null;
JSONObject jsonObj = null; JSONObject feedsObject = null;
json = jParser.getJSONFromUrl(jsonStringUrl);
if (json != null) {
try {
jsonObj = new JSONObject(json);
feedObject = jsonObj.getJSONObject("feed");
For a better understanding visit http://json.parser.online.fr/beta/ and paste your json data there. On the right you have a settings button---> show types You can find what are objects, strings and arrays
See the image below. You were trying get a an object not an array