Parsing multidimensional JSON array ERROR - java

Hi All I am trying to parse a JSON String that contains a multidimensional array. I keep getting the following error in the logs -> W/System.err: org.json.JSONException: No value for nutrients and this error corresponds to the following line -> JSONArray jsonArray1 = jsonObject.getJSONArray("nutrients");
Can someone please help me with this issue. thanks in advance
The JSON String I am trying to parse ->
{
"results": [
{
"id": 654959,
"title": "Pasta With Tuna",
"image": "https://spoonacular.com/recipeImages/654959-312x231.jpg",
"imageType": "jpg",
"nutrition": {
"nutrients": [
{
"title": "Calories",
"amount": 420.823,
"unit": "kcal"
},
{
"title": "Protein",
"amount": 24.4751,
"unit": "g"
},
{
"title": "Fat",
"amount": 10.3277,
"unit": "g"
},
{
"title": "Carbohydrates",
"amount": 57.6915,
"unit": "g"
}
]
}
}
My Java code to parse it ->
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
int id = jsonArray.getJSONObject(i).getInt("id");
String title = jsonArray.getJSONObject(i).getString("title");
String image = jsonArray.getJSONObject(i).getString("image");
Log.i("a", "" + title);
JSONArray jsonArray1 = jsonObject.getJSONArray("nutrients");
for(int e = 0; e < jsonArray1.length(); e++) {
JSONObject jsonObject1 = jsonArray1.getJSONObject(e);
double calories = jsonObject1.getDouble("amount");
Log.i("calories", "" + calories);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}

Your JSON is invalid.
Here is a valid one
{
"results": [
{
"id": 654959,
"title": "Pasta With Tuna",
"image": "https://spoonacular.com/recipeImages/654959-312x231.jpg",
"imageType": "jpg",
"nutrition": {
"nutrients": [
{
"title": "Calories",
"amount": 420.823,
"unit": "kcal"
},
{
"title": "Protein",
"amount": 24.4751,
"unit": "g"
},
{
"title": "Fat",
"amount": 10.3277,
"unit": "g"
},
{
"title": "Carbohydrates",
"amount": 57.6915,
"unit": "g"
}
]
}
}
]
}
Then your Java code
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("results");
JSONObject resultsObject=jsonArray.getJSONObject(0);
int id = resultsObject.getInt("id");
String title = resultsObject.getString("title");
String image =resultsObject.getString("image");
Log.i("a", "" + title);
JSONObject nutrition = resultsObject.getJSONObject("nutrition");
JSONArray nutrients = nutrition.getJSONArray("nutrients");
for(int e = 0; e < nutrients.length(); e++) {
JSONObject jsonObject1 = nutrients.getJSONObject(e);
double calories = jsonObject1.getDouble("amount");
Log.i("calories", "" + calories);
}
} catch (JSONException e) {
e.printStackTrace();
}
Hope Helpful!

Related

How to fetch json inside json inside another json?

I am new to android and json. I want to implement some logic where i can get the data from sub1 from json inside json inside another json.
Is there any way to get that data?
This is how my json file looks like.
{
"Aeronautical": [],
"Automobile": [],
"Civil": [],
"Computer": [
{
"sub1": [
{
"id": "1",
"name": "name1",
"year": "2019",
"url": "some_url"
},
{
"id": "2",
"name": "Name 2",
"year": "2018",
"url": "some url"
},
{
"id": "3",
"name": "Name 4",
"year": "2018",
"url": "some url"
}
]
}
]
}
sub1 is inside another array , so first you should get data from computer array
JSONObject obj = null;
try {
obj = new JSONObject(json);
JSONArray arr = obj.getJSONArray("Computer");
for (int i = 0; i < arr.length(); i++)
{
JSONObject obj_computers = arr.getJSONObject(i);
JSONArray sub1 = obj_computers.getJSONArray("sub1");
for (int j = 0; j < sub1 .length(); j++)
{
JSONObject sub1_data = sub1.getJSONObject(j);
Log.i("test" ,sub1_data.toString());
}
}
} catch (JSONException e) {
e.printStackTrace();
}
The Android SDK includes the org.json lib. You can use the JSONObject class.
String jsonString = /* obtain some JSON however you need to*/;
JSONObject root = new JSONObject(jsonString);
JSONObject sub1 = root.getJSONObject("sub1");
I omitted exception handling, but this is the basic idea.

I am getting error parsing the given value when tried to parse the given json format android

I have the below following type of json structure which is coming from url.
[{
"id": 1,
"name": "TV",
"fromcenter": {
"car": "60 Mins",
"bus": "20 Mins"
},
"location": {
"latitude": -33.7181,
"longitude": 10.3160
}
}, {
"id": 2,
"name": "Fridge",
"fromcenter": {
"car": "30 Mins"
},
"location": {
"latitude": -33.8433,
"longitude": 11.2411
}
}, {
"id": 3,
"name": "Mixie",
"fromcenter": {
"car": "20 Mins",
"bus": "40 Mins"
},
"location": {
"latitude": -3.8910,
"longitude": 11.27777
}
}]
I am able to parse everything except the "bus" because the bus is not available in id 2. So I am getting error as value "bus" not found. JSONException.
Let me know how to solve this? Below is what I tried.
try {
JSONArray array = new JSONArray(response);
goodModelArrayList = new ArrayList<>();
for (int i = 0; i < array.length(); i++) {
JSONObject e = array.getJSONObject(i);
spinnerModel = new MyTransport();
fromcenter = new Fromcenter();
location = new Location();
for (int j = 0; j < e.length(); j++) {
JSONObject object = e.getJSONObject("location");
latitude = object.getString("latitude");
longitude = object.getString("longitude");
}
for (int k = 0; k < e.length(); k++) {
JSONObject object = e.getJSONObject("fromcenter");
car = object.getString("car");
//bus = object.getString("bus"); //I am not able to get the bus. It throws JSONException error.
}
spinnerModel.setId(String.valueOf(e.getString("id")));
spinnerModel.setName(e.getString("name"));
spinnerModel.setFromcenter(car);
//spinnerModel.setBus(bus); //I am not able to store the datas.
spinnerModel.setLocation(latitude);
spinnerModel.setLocations(longitude);
goodModelArrayList.add(spinnerModel);
}
} catch (Exception e) {
e.printStackTrace();
}
you can interrogate if the object has the property before reading it
if (object.has("bus")) {
bus = object.getString("bus");
}
Straight forward one word.
Use optString instead of getString
optString eliminates this issue. Bus is not present in 2nd item.
So use
String bus= object.optString("bus");

How to parse nested last JSON arrays in a single object without parse second JsonArray in Android?

{
"LIST": [
{
"GroupName": "گالری",
"GroupID": "1",
"GType": "gallery1",
"list": [
{
"Title": "food",
"RefType": "app",
"PicUrl": "http://tv.dmedia.ir/images/icon/slide2.jpg",
"RefID": "194"
},
{
"Title": "drink ",
"RefType": "app",
"PicUrl": "http://tv.dmedia.ir/images/icon/slide1.jpg",
"RefID": "199"
}
]
},
{
"GroupName": "ویدئوهای برگزیده",
"GroupID": "2",
"GType": "apk",
"list": [
{
"AppID": "333",
"Packname": "shadkami",
"AppName": "شادکامی و مثبت اندیشی",
"AppSize": 13066,
"VersionCode": "0",
"IconURL": "http://tv.dmedia.ir/paneluser/uploads/files/113.f402cee9889beb52e844012aec28ab0d.mp4/icon/becc1783d1263730b177317f4950f187.jpg",
"IconURL2": "",
"Specials": "0",
"DownloadsCount": "0",
"LikesCount": "0",
"GroupID": "16",
"AppPrice": 0,
"AppAutor": null,
"AppRate": 0,
"GroupType": "1"
},
{
"AppID": "332",
"Packname": "afzayeshetemad",
"AppName": "افزایش اعتماد به نفس",
"AppSize": 25132,
"VersionCode": "0",
"IconURL": "http://tv.dmedia.ir/paneluser/uploads/files/113.b52e30b721705d884832ffc7aa533375.mp4/icon/63c178ab34267b3e25691a7c1b6914c8.jpg",
"IconURL2": "",
"Specials": "0",
"DownloadsCount": "0",
"LikesCount": "0",
"GroupID": "16",
"AppPrice": 0,
"AppAutor": null,
"AppRate": 0,
"GroupType": "1"
}
]
}
]
}
try {
JSONObject object = new JSONObject(respond);
JSONArray jsonArrayLIST = object.getJSONArray("LIST");
ArrayList<ListViewMain> listmain = new ArrayList<>();
ListViewMainAdapter adapter = new ListViewMainAdapter(MainActivity.this, R.layout.list_view_main, listmain);
list_view_main.setAdapter(adapter);
for (int i = 0; i < jsonArrayLIST.length(); i++) {
JSONObject objectLIST = jsonArrayLIST.getJSONObject(i);
JSONArray jsonArraylist = objectLIST.getJSONArray("list");
Toast.makeText(MainActivity.this, jsonArraylist.toString(), Toast.LENGTH_SHORT).show();
for (int j = 0; j < jsonArraylist.length(); j++) {
JSONObject objectlist = jsonArraylist.getJSONObject(j);
String Packname= objectlist.getString("Packname");
Log.i("Log", "SHOW Packname " + Packname);
listmain.add(new ListViewMain(Packname));
adapter.notifyDataSetChanged();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
In can't get String value in third Arraylist "list":[ because is same name with Second ArrayList "list":[.
But when I Toast Second ArrayList I see Second,third Arraylist but I can't get String third value and show nothing in Log or my listView or Toast String Value
how can I access Packname?
you have no Packname in your first array, please revise this
for (int j = 0; j < jsonArraylist.length(); j++) {
JSONObject objectlist = jsonArraylist.getJSONObject(j);
if(objectlist.has("Packname")){
String Packname= objectlist.getString("Packname");
Log.i("Log", "SHOW Packname " + Packname);
listmain.add(new ListViewMain(Packname));
}
}
adapter.notifyDataSetChanged();
please try this

JSON get Array without object

I'm trying to parse this JSON,
{
"listname": "red",
"lists": [
{
"id": "01",
"name": "paw",
"list": [
{
"id": "A",
"name": "pawa",
"bar": "foo"
},
{
"id": "B",
"name": "pawb",
"bar": "foo"
}
]
},
{
"id": "02",
"name": "pew",
"list": [
{
"id": "A",
"name": "pewa",
"bar": "foo"
},
{
"id": "B",
"name": "pewb",
"bar": "foo"
}
]
},
{
"id": "03",
"name": "piw",
"list": [
{
"id": "A",
"name": "piwa",
"bar": "foo"
},
{
"id": "B",
"name": "piwb",
"bar": "foo"
}
]
}
]
}
I put it on Asset Folder and I read it and it converts it to me to String since here all good, the problem is when I'm trying to get the name from each item of lists and trying to get all the names from the list I've tried it doing this :
JSONObject obj = new JSONObject(str);
JSONArray jsonMainArr = obj.getJSONArray("lists"); //first get the lists
for (int i = 0; i < jsonMainArr.length(); i++) {
JSONObject childJSONObject = jsonMainArr.getJSONObject(i);
String name = childJSONObject.getString("name");
Toast.makeText(context, name, Toast.LENGTH_SHORT).show();
}
JSONObject obj = new JSONObject(str);
JSONArray jsonMainArr = obj.getJSONArray("list"); //get the list
for (int i = 0; i < jsonMainArr.length(); i++) {
JSONObject childJSONObject = jsonMainArr.getJSONObject(i);
String name = childJSONObject.getString("name");
Toast.makeText(context, name, Toast.LENGTH_SHORT).show();
}
But it doesn't show anything... what I'm missing?
EDIT
This is how I read the JSON
public static String loadJSONFromAsset(Context ctx, String str) {
String json = null;
try {
InputStream is = ctx.getAssets().open(str);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
Since your "list" is nested in the childJSONObject (from "lists") , nest your for loops to retrieve the this set of values (the JSONobject)
JSONObject obj = new JSONObject(str);
//first get the top-level "lists"
JSONArray jsonMainArr = obj.getJSONArray("lists");
for (int i = 0; i < jsonMainArr.length(); i++) {
JSONObject childJSONObject = jsonMainArr.getJSONObject(i);
String name = childJSONObject.getString("name");
Toast.makeText(context, name, Toast.LENGTH_SHORT).show();
//get the inner "list" from childJSONObject
JSONArray childJSONArray = childJSONObject.getJSONArray("list");
for (int j = 0; j < childJSONArray.length(); j++) {
JSONObject childJSONObjectB = childJSONArray.getJSONObject(j);
String name = childJSONObjectB.getString("name");
Toast.makeText(context, name, Toast.LENGTH_SHORT).show();
}
}

How to get JSONArray exists in another JSONArray?

I have a JSONArray contained in another JSONArray in a JSON Object like the following:
{
"protocol": "test",
"query": [
{
"locked": false,
"ids": [
{
"id": 1,
"locked": false
},
{
"id": 1,
"locked": false
}
]
},
{
"locked": false,
"ids": [
{
"id": 1,
"locked": false
},
{
"id": 1,
"locked": false
}
]
}
],
}
here i want to get the ids arrays, i can get the query arrays like that:
private JSONArray getDB_Query(String json) throws JSONException{
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject(json);
} catch (JSONException e) {
Login.errorMessage.setText(sys_err);
}
JSONArray query = jsonObj.getJSONArray("query");
return query;
}
Now if I want to get the ids, is that true :
jsonObj = new JSONObject(query.toString()); // query is the JSONArray I retrieved from the above method
for(int i= 0; i < query.length(); i ++){
JSONArray ids_query = jsonObj.getJSONArray("ids");
}
update your last for loop like:
for(int i= 0; i < query.length(); i ++){
JSONArray ids_query = query.getJSONObject(i).getJSONArray("ids");
}

Categories

Resources