I'm trying to parse a JSON object in java :
{
"poster_path": "/e3QX3tY0fBR1GuxdP0mwpN16cqI.jpg",
"adult": false,
"overview": "In 1950s Pittsburgh, a frustrated African-American father struggles with the constraints of poverty, racism, and his own inner demons as he tries to raise a family.",
"release_date": "2016-12-16",
"genre_ids": [
18
],
"id": 393457,
"original_title": "Fences",
"original_language": "en",
"title": "Fences",
"backdrop_path": "/jNlCIAcheh0iOuL3kz9x1Wq9WLG.jpg",
"popularity": 10.976374,
"vote_count": 290,
"video": false,
"vote_average": 6.7
},
But I get a JSONException when I try to access the values for poster_path(org.json.JSONException: No value for poster_path) and release_date(org.json.JSONException: No value for release_date)
ArrayList<MovieModel> results = new ArrayList<MovieModel>();
String streamAsString = result;
try{
JSONObject jsonObject = new JSONObject(streamAsString);
JSONArray array = (JSONArray) jsonObject.get("results");
for (int i = 0; i < array.length(); i++) {
JSONObject c = array.getJSONObject(i);
JSONObject jsonMovie = array.getJSONObject(i);
MovieModel movieModel= new MovieModel();
movieModel.setMovieTitle(jsonMovie.getString("title"));
movieModel.setMovieGenre("na");;
String strImgURL=jsonObject.getString("poster_path").substring(2);
movieModel.setImgURL("");
movieModel.setMovieYear(jsonObject.getString("release_date"));
results.add((movieModel));
}
}
catch(JSONException j)
{
System.err.println(j);
Log.d(DEBUG_TAG, "Error parsing JSON. String was: " + j.toString());
}
Not sure what could be causing this error
You're trying to get the poster_path and release_date values from the outer JSONObject, the one that has everything (including the JSONArray that contains the individual movies).
In the loop, just use jsonMovie instead of jsonObject:
for (int i = 0; i < array.length(); i++) {
JSONObject jsonMovie = array.getJSONObject(i);
MovieModel movieModel= new MovieModel();
movieModel.setMovieTitle(jsonMovie.getString("title"));
movieModel.setMovieGenre("na");
String strImgURL=jsonMovie.getString("poster_path").substring(2);
movieModel.setImgURL("");
movieModel.setMovieYear(jsonMovie.getString("release_date"));
results.add((movieModel));
}
Related
I have problem when I try to get data from a JSON array in Android Studio.
I want to get data from year 2015, 2016 and 2018 populate them in different textviews.
This is my JSON:
"data": [
{
"id": "7",
"kecamatan": "Blambangan Umpu",
"year": {
"2015": {
"id": "27",
"value": "60200"
},
"2016": {
"id": "41",
"value": "61516"
},
"2018": {
"id": "7",
"value": ""
}
},
"avg": 2.14
},
and this is my mainactivity
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray array = jsonObject.getJSONArray("data");
// JSONArray array = new JSONArray(s);
for (int i = 0; i < array.length(); i ++) {
JSONObject o = array.getJSONObject(i);
String id = o.getString("id");
String kec = o.getString("kecamatan");
String avg = o.getString("avg");
String tahun = o.getString("year");
// JSONArray array2 = o.getJSONArray("year");
// for (int j = 0; j<array2.length(); j++) {
// JSONObject p = array2.getJSONObject(j);
// String value = p.getString("value");
ListItem item = new ListItem(id, kec, avg, tahun, avg);
listItems.add(item);
// }
}
adapter = new MyAdapter(listItems, getApplicationContext());
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
year is a JSONObject with 2015,2016 and 2018 as keys and JSONObject as values, So get year JSONObject and then get keys and values by iterating it
for (int i = 0 ; i<array.length(); i++) {
JSONObject o = array.getJSONObject(i);
String id = o.getString("id");
String kec = o.getString("kecamatan");
String avg = o.getString("avg");
JSONObject yearObject = o.JSONObject("year"); //get JSONObject
Iterator<String> itr = yearObject.keys();
while(itr.hasNext()) {
String year = itr.next();
JSONObject obj = o.get("year"); //2015
System.out.println(obj.getString("id")); //27
System.out.println(obj.getString("value")); //60200
}
//Add required fields into `ListItem`
ListItem item = new ListItem(id,kec,avg,tahun,avg);
listItems.add(item);
}
I have been using the the Json library to try and parse the following Json data:
{"dailygameschedule": {
"lastUpdatedOn": "2016-12-19 12:32:56 AM",
"gameentry": [
{
"id": "37705",
"date": "2016-04-03",
"time": "1:30PM",
"awayTeam": {
ID: "133",
City: "St. Louis",
Name: "Cardinals"
Abbreviation: "STL"
},
"homeTeam": {
"ID": "132",
"City": "Pittsburgh",
"Name": "Pirates",
"Abbreviation": "PIT"
},
"location": "PNC Park"
},
...
]
}
I cant figure out how to get the "gameentry" array. I was looking at other threads for guidance but it is not quite working for me. Heres what I have so far:
JSONObject obj = new JSONObject(todaysGames);
String pageName = obj.getJSONObject("dailygameschedule").getString("lastUpdatedOn");
System.out.println("2 asdfasdf "+ pageName);
JSONArray arr = obj.getJSONArray("gameentry");
for (int i = 0; i < arr.length(); i++)
{
//String post_id = arr.getJSONObject(i).getString("id");
System.out.println(arr.getJSONObject(i).getString("awayTeam.ID"));
}
There error that im getting is:
Exception in thread "main" org.json.JSONException:
JSONObject["gameentry"] not found.
Thanks!
Try this,
JSONArray arr=obj.getJSONObject("dailygameschedule").getJSONArray("gameentry");
for (int i = 0; i < arr.length(); i++)
{
JSONObject obj = arr.getJSONObject(i);
String id = obj.getString("id");
JSONObject awayTeam_obj=obj.getJSONObject("awayTeam");
String awayTeam_ID = awayTeam_obj.getString("ID");
String awayTeam_City = awayTeam_obj.getString("City");
String awayTeam_Name = awayTeam_obj.getString("Name");
JSONObject homeTeam_obj=obj.getJSONObject("homeTeam");
String homeTeam_ID = homeTeam_obj.getString("ID");
String homeTeam_City = homeTeam_obj.getString("City");
String homeTeam_Name = homeTeam_obj.getString("Name");
}
gameentry array is a member of dailygameschedule object, so you need to access it first.
JSONArray arr = obj.getJSONObject("dailygameschedule").getJSONArray("gameentry");
for (int i = 0; i < arr.length(); i++)
{
//String post_id = arr.getJSONObject(i).getString("id");
System.out.println(arr.getJSONObject(i).getString("awayTeam.ID"));
}
That's not a valid JSON object, Just add '}' and gameentry not a root element you should get dailygamesschedule first and then get the gameentry
This is my JSON:
{
"data": [
{
"id": 1,
"Name": "Choc Cake",
"Image": "1.jpg",
"Category": "Meal",
"Method": "",
"Ingredients": [
{
"name": "1 Cup Ice"
},
{
"name": "1 Bag Beans"
}
]
},
{
"id": 2,
"Name": "Ice Cake",
"Image": "dfdsfdsfsdfdfdsf.jpg",
"Category": "Meal",
"Method": "",
"Ingredients": [
{
"name": "1 Cup Ice"
}
]
}
]
}
And this is how I am getting the id and name, you can see this part works fine in returning JSON values that are not array values.
//getting whole json string
JSONObject jsonObj = new JSONObject(jsonStr);
//extracting data array from json string
JSONArray ja_data = jsonObj.getJSONArray("data");
int length = jsonObj .length();
//loop to get all json objects from data json array
for(int i=0; i<length; i++)
{
JSONObject jObj = ja_data.getJSONObject(i);
Toast.makeText(this, jObj.getString("Name"), Toast.LENGTH_LONG).show();
// getting inner array Ingredients
JSONArray ja = jObj.getJSONArray("Ingredients");
int len = ja.length();
}
Now i'm trying to get the values from the ingredients array and I am not sure how to get them? This is what I have been trying thus far.
//getting whole json string
JSONObject jsonObj = new JSONObject(jsonStr);
//extracting data array from json string
JSONArray ja_data = jsonObj.getJSONArray("data");
int length = jsonObj .length();
//loop to get all json objects from data json array
for(int i=0; i<length; i++)
{
JSONObject jObj = ja_data.getJSONObject(i);
Toast.makeText(this, jObj.getString("Name"), Toast.LENGTH_LONG).show();
// getting inner array Ingredients
JSONArray ja = jObj.getJSONArray("Ingredients");
int len = ja.length();
// getting json objects from Ingredients json array
for(int j=0; j<len; j++)
{
JSONObject json = ja.getJSONObject(j);
Toast.makeText(this, json.getString("name"), Toast.LENGTH_LONG).show();
}
}
But doing it this way is not working, how can I get it to work?
Solved, use array list of string to get name from Ingredients. Use below code:
JSONObject jsonObj = new JSONObject(jsonStr);
//extracting data array from json string
JSONArray ja_data = jsonObj.getJSONArray("data");
int length = ja_data.length();
//loop to get all json objects from data json array
for(int i=0; i<length; i++){
JSONObject jObj = ja_data.getJSONObject(i);
Toast.makeText(this, jObj.getString("Name"), Toast.LENGTH_LONG).show();
// getting inner array Ingredients
JSONArray ja = jObj.getJSONArray("Ingredients");
int len = ja.length();
ArrayList<String> Ingredients_names = new ArrayList<>();
for(int j=0; j<len; j++){
JSONObject json = ja.getJSONObject(j);
Ingredients_names.add(json.getString("name"));
}
}
JSONObject jsonObject =new JSONObject(jsonStr);
JSONArray jsonArray = jsonObject.getJSONArray("data");
for(int i=0;i<jsonArray.length;i++){
JSONObject json = jsonArray.getJSONObject(i);
String id = json.getString("id");
String name=json.getString("name");
JSONArray ingArray = json.getJSONArray("Ingredients") // here you are going to get ingredients
for(int j=0;j<ingArray.length;j++){
JSONObject ingredObject= ingArray.getJSONObject(j);
String ingName = ingredObject.getString("name");//so you are going to get ingredient name
Log.e("name",ingName); // you will get
}
}
JSONObject jsonObj = new JSONObject(jsonString);
JSONArray jArray = jsonObj.getJSONArray("data");
int length = jArray.length();
for(int i=0; i<length; i++)
{
JSONObject jObj = jArray.getJSONObject(i);
String id = jObj.optString("id");
String name=jObj.optString("name");
JSONArray ingredientArray = jObj.getJSONArray("Ingredients");
int size = ingredientArray.length();
ArrayList<String> Ingredients = new ArrayList<>();
for(int j=0; j<size; j++)
{
JSONObject json = ja.getJSONObject(j);
Ingredients.add(json.optString("name"));
}
}
Your int length = jsonObj.length(); should be int length = ja_data.length();
Gson gson = new Gson();
Type listType = new TypeToken<List<Data>>() {}.getType();
List<Data> cartProductList = gson.fromJson(response.body().get("data"), listType);
Toast.makeText(getContext(), ""+cartProductList.get(0).getCity(), Toast.LENGTH_SHORT).show();
I am getting the following as a String response from a webserveice:
[
[
{
"dgtype": "adhoc",
"subtypename": "Person",
"subtypedesc": "null",
"summary": "Junaid (Self)",
"subtype": "person",
"birthdate": "1995-1-23 ",
"name": "Junaid (Self)"
},
{
"dgtype": "adhoc",
"subtypename": "Job",
"subtypedesc": "null",
"summary": "Exa",
"subtype": "person",
"birthdate": "2010-01-30",
"name": "Junaid (Self)"
}
]
]
In Java I am trying to do the following:
JSONArray jArray = new JSONArray(result);
System.out.println("Response: "+jArray);
for(int i = 0; i<= jArray.length(); i++){
try {
JSONObject oneObject = jArray.getJSONObject(i);
String dgtype = oneObject.getString("dgtype");
String subtypename = oneObject.getString("subtypename");
String subtypedesc = oneObject.getString("subtypedesc");
String summary = oneObject.getString("summary");
String subtype = oneObject.getString("subtype");
String birthdate = oneObject.getString("birthdate");
String name = oneObject.getString("name");
System.out.println(i);
System.out.println("dgtype: "+dgtype);
System.out.println("subtypename: "+subtypename);
System.out.println("subtypedesc: "+subtypedesc);
System.out.println("summary: "+summary);
System.out.println("subtype: "+subtype);
System.out.println("birthdate: "+birthdate);
System.out.println("name: "+name);
} catch (JSONException e) {
System.out.println("JSON Exception: "+e);
}
}
However I am getting the following exception:
JSON Exception: org.json.JSONException: Value
[
{
"dgtype": "adhoc",
"subtypename": "Person",
"subtypedesc": "null",
"summary": "Junaid (Self)",
"subtype": "person",
"birthdate": "1995-1-23 ",
"name": "Junaid (Self)"
},
{
"dgtype": "adhoc",
"subtypename": "Job",
"subtypedesc": "null",
"summary": "Exa",
"subtype": "person",
"birthdate": "2010-01-30",
"name": "Junaid (Self)"
}
]
at 0 of type org.json.JSONArray cannot be converted to JSONObject
JSON Exception: org.json.JSONException: Index 1 out of range [0..1)
I am following this example. Where am I going wrong? Also notice the missing long brackets in the exception snippet.
You have two arrays, one is within another:
[
[
//Your objects
]
]
You could either change data format so it only has one array, or modify your code:
JSONArray outer = new JSONArray(result);
JSONArray jArray = outer.getJSONArray(0);
jArray JSONArray contain another JSONArray which contain JSONObeject so first get JSONArray and then get all JSONObject from it:
JSONArray oneArray = jArray.getJSONArray(i);
for(int j = 0; j<= oneArray.length(); j++){
JSONObject oneObject = oneArray.getJSONObject(j);
// get dgtype,subtypename,subtypedesc,.. from oneObject
}
As it says, 'JSONArray cannot be converted to JSONObject', You have an array in another array, so
JSONArray jArray1 = new JSONArray(result);
then
JSONArray jArray = jArray1.getJSONArray(0);
Now it will work.
for(int i = 0; i<= jArray.length(); i++){
final JSONArray innerArray = jArray.getJSONArray(i);
for (int a = 0; a < innerArray.length(); a++) {
try {
final JSONObject oneObject = innerArray.getJSONObject(i);
String dgtype = oneObject.getString("dgtype");
String subtypename = oneObject.getString("subtypename");
String subtypedesc = oneObject.getString("subtypedesc");
String summary = oneObject.getString("summary");
String subtype = oneObject.getString("subtype");
String birthdate = oneObject.getString("birthdate");
String name = oneObject.getString("name");
System.out.println(i);
System.out.println("dgtype: "+dgtype);
System.out.println("subtypename: "+subtypename);
System.out.println("subtypedesc: "+subtypedesc);
System.out.println("summary: "+summary);
System.out.println("subtype: "+subtype);
System.out.println("birthdate: "+birthdate);
System.out.println("name: "+name);
} catch (JSONException e) {
System.out.println("JSON Exception: "+e);
}
}
}
Each news entry has three things : title,contentand date.
The entries are retrieved from a database and I would like to read them in my application using JSONObject and JSONArray. However, I do not know how to use these classes.
Here is my JSON string:
[
{
"news":{
"title":"5th title",
"content":"5th content",
"date":"1363197493"
}
},
{
"news":{
"title":"4th title",
"content":"4th content",
"date":"1363197454"
}
},
{
"news":{
"title":"3rd title",
"content":"3rd content",
"date":"1363197443"
}
},
{
"news":{
"title":"2nd title",
"content":"2nd content",
"date":"1363197409"
}
},
{
"news":{
"title":"1st title",
"content":"1st content",
"date":"1363197399"
}
}
]
Your JSON string is a JSONArray of JSONObject which then contain an inner JSONObject called "news".
Try this for parsing it:
JSONArray array = new JSONArray(jsonString);
for(int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
JSONObject innerObject = obj.getJSONObject("news");
String title = innerObject.getString("title");
String content = innerObject.getString("content");
String date = innerObject.getString("date");
/* Use your title, content, and date variables here */
}
First of all, your JSON structure is not ideal. You have an array of objects, with each object having a single object in it. However, you could read it like this:
JSONArray jsonArray = new JSONArray (jsonString);
int arrayLength = jsonArray.length ();
for (int counter = 0; counter < arrayLength; counter ++) {
JSONObject thisJson = jsonArray.getJSONObject (counter);
// we finally get to the proper object
thisJson = thisJson.getJSONObject ("news");
String title = thisJson.getString ("title");
String content = thisJson.getString ("content");
String date = thisJson.getString ("date");
}
However!
You could do better if you change your JSON to look like the following:
[
{
"title": "5th title",
"content": "5th content",
"date": "1363197493"
},
{
"title": "4th title",
"content": "4th content",
"date": "1363197454"
}
]
Then, you could parse it as follows:
JSONArray jsonArray = new JSONArray (jsonString);
int arrayLength = jsonArray.length ();
for (int counter = 0; counter < arrayLength; counter ++) {
// we don't need to look for a named object any more
JSONObject thisJson = jsonArray.getJSONObject (counter);
String title = thisJson.getString ("title");
String content = thisJson.getString ("content");
String date = thisJson.getString ("date");
}