Android JSON access thumbnail element - java

I have this json result http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=25&q=http://www.abc.net.au/news/feed/51120/rss.xml
I am trying to access the thumbnails for each news article located in entries>mediaGroups>contents>thumbnails>url
However I am unsure of how to access that deep in the element. This is my code so far.
public List<NewsObj> constructJSON(String jsonIN){
ArrayList<NewsObj> newsList = new ArrayList<>();
try{
//add more levels to extract json
JSONObject jsonObject1 = new JSONObject(jsonIN);
String responseData = jsonObject1.getString("responseData");
Log.d("RECEIVEJSONOBJECTLEVEL1",responseData);
JSONObject jsonObject2 = new JSONObject(responseData);
String feed = jsonObject2.getString("feed");
Log.d("RECEIVEJSONOBJECTLEVEL2",feed);
JSONObject jsonObject3 = new JSONObject(feed);
String entries = jsonObject3.getString("entries");
Log.d("RECEIVEJSONOBJECTLEVEL3", entries);
JSONArray jsonArray1 = new JSONArray(entries);
for(int i=0; i<jsonArray1.length();i++){
JSONObject mediaGroups = jsonArray1.getJSONObject(i);
String mediaItems = mediaGroups.getString("mediaGroups");
String title = mediaGroups.getString("title");
String url = mediaGroups.getString("link");
String description = mediaGroups.getString("contentSnippet");
String publishedDate = mediaGroups.getString("publishedDate");
// main information for news article
//for further thumbnail sizes?
JSONArray jsonArray2 = new JSONArray(mediaItems);
for(int j=0;j<jsonArray2.length();j++){
JSONObject contents = jsonArray2.getJSONObject(j);
String contentItems = contents.getString("contents");
Log.d("RECEIVEJSONOBJECTARRAY2",contentItems);
JSONArray jsonArray3 = new JSONArray(contentItems);
for(int k=0;k<jsonArray3.length();k++){
JSONObject items = jsonArray3.getJSONObject(k);
//too specific
String imgurl = items.getString("url");
//Log.d("RECEIVEJSONOBJECTARRAY3",imgurl);
NewsObj aObj = new NewsObj(title, imgurl,url, publishedDate);
newsList.add(aObj);
}
}
}
}catch (JSONException e){
e.printStackTrace();
Log.d("RECEIVEJSONERROR",e.toString());
}
return newsList;
}

You just need to make another JSONArray for thumbnails. For Reference See Example
Try This
public List<NewsObj> constructJSON(String jsonIN){
ArrayList<NewsObj> newsList = new ArrayList<>();
try{
//add more levels to extract json
JSONObject jsonObject1 = new JSONObject(jsonIN);
String responseData = jsonObject1.getString("responseData");
Log.d("RECEIVEJSONOBJECTLEVEL1",responseData);
JSONObject jsonObject2 = new JSONObject(responseData);
String feed = jsonObject2.getString("feed");
Log.d("RECEIVEJSONOBJECTLEVEL2",feed);
JSONObject jsonObject3 = new JSONObject(feed);
String entries = jsonObject3.getString("entries");
Log.d("RECEIVEJSONOBJECTLEVEL3", entries);
JSONArray jsonArray1 = new JSONArray(entries);
for(int i=0; i<jsonArray1.length();i++){
JSONObject mediaGroups = jsonArray1.getJSONObject(i);
String mediaItems = mediaGroups.getString("mediaGroups");
String title = mediaGroups.getString("title");
String url = mediaGroups.getString("link");
String description = mediaGroups.getString("contentSnippet");
String publishedDate = mediaGroups.getString("publishedDate");
// main information for news article
//for further thumbnail sizes?
JSONArray jsonArray2 = new JSONArray(mediaItems);
for(int j=0;j<jsonArray2.length();j++){
JSONObject contents = jsonArray2.getJSONObject(j);
String contentItems = contents.getString("contents");
Log.d("RECEIVEJSONOBJECTARRAY2",contentItems);
JSONArray jsonArray3 = new JSONArray(contentItems);
for(int k=0;k<jsonArray3.length();k++){
JSONObject items = jsonArray3.getJSONObject(k);
//too specific
String imgurl = items.getString("url");
//Log.d("RECEIVEJSONOBJECTARRAY3",imgurl);
String thumbnails = items.getString("thumbnails");
JSONArray jsonArray4 = new JSONArray(thumbnails);
for(int l=0;l<jsonArray4.length();l++){
JSONObject thumbnails1 = jsonArray4.getJSONObject(l);
String height = items.getString("height");
String width = items.getString("width");
String thumburl = items.getString("url");
}
NewsObj aObj = new NewsObj(title, imgurl,url, publishedDate);
newsList.add(aObj);
}
}
}
}catch (JSONException e){
e.printStackTrace();
Log.d("RECEIVEJSONERROR",e.toString());
}
return newsList;
}

Related

Cannot convert java string to JSON Array in Android

Below is the query which is fetching the data from the MySql Database but the issue is that in browser it successfully outputs the data but in Android app it gives the error which is below
Java.Long.String Cannot Convert to JsonArray
if($stem=$con->prepare("select question from MCQs where c_id=$c_id ")){
$stem->execute ();
$stem->bind_result($question);
$budget=array();
while($stem->fetch())
{
$temp=array();
$temp['question']=$question;
array_push($budget,$temp);
}
echo json_encode($budget);
Below is the Android Side Java Code for the JSON
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
JSONArray jsonArray = jsonObject.getJSONArray("data");
if (success.equals("1")) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
String questions = jsonObject1.getString("question").trim();
final String opt0ne = jsonObject1.getString("option1").trim();
;
String opttwo = jsonObject1.getString("option2").trim();
;
String optthree = jsonObject1.getString("option3").trim();
final String correctt = jsonObject1.getString("correct").trim();
JSONObject json = new JSONObject(result);
JSONArray jArray = json.getJSONArray("data");
for (int i=0;jArray.length(); i++)
{
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
//try this
String msg= jsonObject1.getString("success");
}

Having trouble finding the right JSON path for android project

JSONObject baseJsonResponse = new JSONObject(newsJSON);
JSONObject responseObj = baseJsonResponse.getJSONObject("response");
JSONArray resultArray = responseObj.getJSONArray("results");
for (int i =0;i<resultArray.length();i++){
String sectionName = resultArray.getString("sectionName");}
I want to get the section name for this url:
https://content.guardianapis.com/search?api-key=e11b8d10-d6ef-4fb7-9c12-094c58d37687
You can get Json Value Like this.
JSONObject baseJsonResponse = new JSONObject(newsJSON);
JSONObject responseObj = null;
try {
responseObj = baseJsonResponse.getJSONObject("response");
JSONArray resultArray = responseObj.getJSONArray("results");
int size = resultArray.length();
for (int i =0;i<size;i++){
JSONObject myJson = resultArray.getJSONObject(i);
String sectionName = myJson.getString("sectionName");
}
} catch (JSONException e) {
e.printStackTrace();
}

Parsing another JSON Format

So here's the following code :
jObj = new JSONObject(valeurARenvoyer);
hauteur = jObj.getString("niveauEau");
debit = jObj.getString("debit");
date = jObj.getString("dateReleve");
batterie = jObj.getString("chargeBatterie");
presence = jObj.getString("etatPerimetrique");
bat = jObj.getString("chargeBatterie");
So i used this code to parse a JSON which was like that :
{"id":"15","id_Station":"Artiguelouve","Date_Releve":"2017-02-16 16:07:41","Niveau_Eau":"29","Charge_Batterie":"9","Etat_Perimetrique":"0","Debit":"13.35"}
It worked well, but now my JSON response looks like that :
{"Station":"Artiguelouve","debit":[{"niveauEau":0,"debit":32.5,"dateReleve":{"date":"2017-06-08 15:59:03","timezone_type":3,"timezone":"Europe\/Paris"},"idStation":"Artiguelouve","etatPerimetrique":true,"chargeBatterie":14590}]}
With this response i can't find how to parse this.
valeurARenvoyer is my JSON. Can you have any solution to do that please ?
add this code to get response
JSONObject jsonObject = new JSONObject(jsonResponse);//put your json response
JSONArray jsonArray = null;
try {
String station = jsonObject.getString("Station");
jsonArray = jsonObject.getJSONArray("debit");
for(int i=0;i<jsonArray.length();i++)
{
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
int niveauEau = jsonObject1.getInt("niveauEau");
int debit = jsonObject1.getInt("debit");
String isStation = jsonObject1.getString("idStation");
boolean etatPerimetrique = jsonObject1.getBoolean("etatPerimetrique");
int chargeBatterie = jsonObject1.getInt("chargeBatterie");
JSONObject jsonObject2 = jsonObject1.getJSONObject("dateReleve");
String date = jsonObject2.getString("date");
int timezone_type = jsonObject2.getInt("timezone_type");
String timezone = jsonObject2.getString("timezone");
}
} catch (JSONException e) {
e.printStackTrace();
}
try this code
try {
JSONObject jsonObject = new JSONObject(valeurARenvoyer);
JSONArray jsonArray = jsonObject.getJSONArray("debit");
for(int i = 0; i < jsonArray.length(); i++){
// you can get niveauEau, debit, idStation, etatPerimetrique,
// chargeBatterie, dateReleve JsonObject values in this loop
}
} catch (JSONException e) {
e.printStackTrace();
}

Trying to parse JSON in Android

How would you suggest me to parse this JSON:
{"17": {"user_name": "test1"}, "18": {"user_name": "test5"}, "19": {"user_name": "test9"}}
I need to get "username",but i cant find the way to do it. Maybe i should change JSON to something like that:
[{"user_name": "test1"},{"user_name": "test5"},{"user_name": "test9"}]
This way i tried to get "user_name"s:
try {
List<String> allNames = new ArrayList<String>();
String str = "[{"user_name": "test1"},{"user_name": "test5"},{"user_name": "test9"}]";
JSONObject json = new JSONObject(str);
for ( int i = 0; i < json.length() ; i++)
{
JSONObject actor = json.getJSONObject(i);
String user_name = actor.getString("user_name");
allNames.add(user_name);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
But then i get Problem with that line:
JSONObject actor = json.getJSONObject(i);
Android studio tells me that JSONObject cannot be applied to int(i). I have no idea why it doesn't work.
Can somebody please give me some hint, tutorial or an example?
Much appreciated !
The method JSONObject.getJSONObject requires a String argument (the name or key of the object), not an int. In your case, the keys are "17", "18" and "19". To get all keys, use the JSONObject.keys() method:
JSONObject json = new JSONObject(str);
Iterator<String> keyIterator = json.keys();
while (keyIterator.hasNext()) {
JSONObject actor = json.getJSONObject(keyIterator.next());
String user_name = actor.getString("user_name");
allNames.add(user_name);
}
Android studio tells me that JSONObject cannot be applied to int(i)
Because JSONObject.getJSONObject method takes key name as String instead of int. and keys in posted json is 17,18,... to access inner JSONObject.
To get all user_name from JSONObject,need to get all keys:
Iterator<String> iter = json.keys();
while (iter.hasNext()) {
String key = iter.next();
JSONObject actor = json.getJSONObject(key);
String user_name = actor.getString("user_name");
allNames.add(user_name);
}
Change your code like this
try {
List<String> allNames = new ArrayList<String>();
String str = "[{"user_name": "test1"},{"user_name": "test5"},{"user_name": "test9"}]";
JSONOArray jsonArray = new JSONOArray(str);
for ( int i = 0; i < jsonArray .length() ; i++)
{
JSONObject actor = jsonArray.getJSONObject(i);
String user_name = actor.getString("user_name");
allNames.add(user_name);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if you use the Gson library it's very easy.
String json = "{\"17\": {\"user_name\": \"test1\"}, \"18\": {\"user_name\": \"test5\"}, \"19\": {\"user_name\": \"test9\"}}";
Gson gson = new GsonBuilder().create();
Map<String,User> users = gson.fromJson(json, new TypeToken<Map<String,User> >(){}.getType());
for(String key : users.keySet()) {
Log.d("DEBUG",key+" -> "+users.get(key).getUser_name());
}
The User class is a simple POJO like:
public class User {
private String user_name;
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
}
str = {"17": {"user_name": "test1"}, "18": {"user_name": "test5"}, "19": {"user_name": "test9"}}
JSONObject ob1 = new JSONObject(str)
JSONObject ob2 = ob1.getJSONObject("17");
String userName = ob2.getString("user_name");
str = [{"user_name": "test1"},{"user_name": "test5"},{"user_name": "test9"}]
List<String> allNames = new ArrayList<String>();
JSONArray jsonArray = new JSONArray("str");
for(i=0; i < jsonArray.length(); i++){
JSONObject ob = jsonArray.getJSONObject(i);
allNames.add(ob.getString("user_name")
}
you are trying to parse JSONArray into JSONObject at
JSONObject json = new JSONObject(str);
use the below code.....
try {
List<String> allNames = new ArrayList<String>();
String str = "[{"user_name": "test1"},{"user_name": "test5"},{"user_name": "test9"}]";
JSONArray json = new JSONArray(str);
for ( int i = 0; i < json.length() ; i++)
{
JSONObject actor = json.getJSONObject(i);
String user_name = actor.getString("user_name");
allNames.add(user_name);
}
} catch (JSONException e) {
// TODO Auto-generated catch block`enter code here`
e.printStackTrace();
}

Get JSON Array into strings.

I have a webservice which returns a JSON array in this format:
[{"imageid":"3","userid":"1","imagepath":"SLDFJNDSKJFN","filterid":"1","dateadded":"2014-05-06 21:20:18.920257","public":"t"},
{"imageid":"4","userid":"1","imagepath":"dsfkjsdkfjnkjdfsn","filterid":"1","dateadded":"2014-05-06 21:43:37.642748","public":"t"}]
I need to get all the attributes seperately? How would I do this?
I know how to do it with JSONObject if there is just 1 thing being returned, but how does it work when multiple items are returned?
Thanks
try {
JSONArray jArray = new JSONArray(jsonString);
String s = new String();
for (int i = 0; i < jArray.length(); i++) {
s = jArray.getJSONObject(i).getString("imageid").toString();
s = jArray.getJSONObject(i).getString("userid").toString();
}
} catch (JSONException je) {
}
Create an Object class with all variables, create a List for this Object, add all objects in your JSONArray to the list, use the one you need.
List<YourObject> objList = new ArrayList<YourObject>();
JSONArray a = new JSONArray(response);
int size = a.length();
for (int i=0 ; i<size ; i++){
JSONObject aa = a.getJSONObject(i);
String id = aa.getString("imageid");
String userid = aa.getString("userid");
String imagepath = aa.getString("imagepath");
String filterid = aa.getString("filterid");
String dateadded = aa.getString("dateadded");
String publicText = aa.getString("public");
YourObject obj = new YourObject(id,userid,imagepath,filterid,dateadded,publicText);
objList.add(obj);
}
So what you are having here is some JSON objects inside a JSON array.
What you want to do is this:
JSONArray array = ...;
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
// Extract whatever you want from the JSON object.
}
I hope it helped.
You can use JSONArray to parse array of JSON response.
private void parseJsonArray(String response) {
try {
JSONArray array = new JSONArray(response);
for(int i=0;i<array.length();i++){
JSONObject jsonObject = array.getJSONObject(i);
String ImageId = jsonObject.getString("imageid");
Log.v("JSON Parser", "ImageId: "+ImageId);
}
} catch (Exception e) {
e.printStackTrace();
}
}

Categories

Resources