I want to get the three JSONArrays below with the help of each array's index
My JSON:
{
[
{
"id": 3429,
"name": "Mass Effect: Andromeda",
"prix": 100,
"description": "The newest Mass Effect instalement",
"quantiteDisponible": 400,
"image": "https://res.cloudinary.com/igdb/image/upload/t_screenshot_big/xtn9vhiek0kdpetibmvw.webp"
},
{
"id": 3430,
"name": "Halo 5: Guardians",
"prix": 10,
"description": "Not the best Halo",
"quantiteDisponible": 420,
"image": "https://res.cloudinary.com/igdb/image/upload/t_cover_big/rzjnrhuv5rozj52g9aq3.webp"
}
],
[
{
"id": 3431,
"name": "Bloodbonrne",
"prix": 20,
"description": "Better than you",
"quantiteDisponible": 612,
"image": "https://res.cloudinary.com/igdb/image/upload/t_cover_big/fivw1ogfjw266t72kcn2.webp"
},
{
"id": 3432,
"name": "Dark Souls 3",
"prix": 60,
"description": "Prepare to die",
"quantiteDisponible": 604,
"image": "https://res.cloudinary.com/igdb/image/upload/t_cover_big/ofu6ewg0tzdt5vmzcj9q.webp"
}
],
[
{
"id": 3433,
"name": "Mario Sunshine",
"prix": 40,
"description": "Mario Sunshine best Mario Game",
"quantiteDisponible": 11,
"image": "https://res.cloudinary.com/igdb/image/upload/t_cover_big/ok5aq7j375uaxp59zr2g.webp"
},
{
"id": 3434,
"name": "Outlaw Golf",
"prix": 60,
"description": "Outlaw Golf is back with a bang!",
"quantiteDisponible": 10,
"image": "https://res.cloudinary.com/igdb/image/upload/t_cover_big/cxgtamh2r6z7tezfs1og.webp"
}
]
}
I don't know if it's possible and would greatly appreciate any help
First I read the JSON store it into a variable:
JSONObject object = new JSONObject(JsonText);
System.out.println(object.length());
The System.out.println returns 3, so it knows we're talking about the 3 JSON Arrays.
And this how I try and get the Arrays
for (int i = 0; i < object.length(); i++){
JSONArray array = object.getJSONArray(HELP);
}
you can try this snippet
for (int i = 0; i < getArray.length(); i++) {
JSONObject objects = getArray.getJSONObject(i);
Iterator key = objects.keys();
while (key.hasNext()) {
String k = key.next().toString();
System.out.println("Key : " + k + ", value : "
+ objects.getString(k));
}
// System.out.println(objects.toString());
System.out.println("-----------");
}
You have to pass the value of i. But object.getJSONArray() accepts only string.So you can use like this.
JSONObject obj=new JSONObject(JsonText);
for(int i=0;i<obj.length();i++){
try {
JSONArray jsonArray=obj.getJSONArray(String.valueOf(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
Related
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!
So I am incredibly new to Java and am needing help parsing a JSON response. I already have the method in which I am using to do so, but need help figuring out what exactly I am doing wrong.
I am using an API to retrieve recipes from a site. I am trying to get a list of recipes ("hits" in this case I assume?) that I can then show to the user.
Obviously I need the recipe name ("label" in this case) and other information. Can anyone help me?
Here is the response api response I am getting:
{
"q": "chicken",
"from": 0,
"to": 10,
"more": true,
"count": 168106,
"hits": [
{
"recipe": {
"uri": "http://www.edamam.com/ontologies/edamam.owl#recipe_b79327d05b8e5b838ad6cfd9576b30b6",
"label": "Chicken Vesuvio",
"image": "https://www.edamam.com/web-img/e42/e42f9119813e890af34c259785ae1cfb.jpg",
"source": "Serious Eats",
"url": "http://www.seriouseats.com/recipes/2011/12/chicken-vesuvio-recipe.html",
"shareAs": "http://www.edamam.com/recipe/chicken-vesuvio-b79327d05b8e5b838ad6cfd9576b30b6/chicken",
"yield": 4,
"dietLabels": [
"Low-Carb"
],
"healthLabels": [],
"cautions": [],
"ingredientLines": [
"1/2 cup olive oil",
"5 cloves garlic, peeled",
"2 large russet potatoes, peeled and cut into chunks",
"1 3-4 pound chicken, cut into 8 pieces (or 3 pound chicken legs)",
"3/4 cup white wine",
"3/4 cup chicken stock",
"3 tablespoons chopped parsley",
"1 tablespoon dried oregano",
"Salt and pepper",
"1 cup frozen peas, thawed"
],
"ingredients": [
{
"text": "1/2 cup olive oil",
"weight": 108
},
{
"text": "5 cloves garlic, peeled",
"weight": 15
},
{
"text": "2 large russet potatoes, peeled and cut into chunks",
"weight": 532.5
},
{
"text": "1 3-4 pound chicken, cut into 8 pieces (or 3 pound chicken legs)",
"weight": 1587.5732
},
{
"text": "3/4 cup white wine",
"weight": 169.5
},
{
"text": "3/4 cup chicken stock",
"weight": 180
},
{
"text": "3 tablespoons chopped parsley",
"weight": 11.4
},
{
"text": "1 tablespoon dried oregano",
"weight": 6
},
{
"text": "Salt and pepper",
"weight": 16.46384
},
{
"text": "Salt and pepper",
"weight": 8.23192
},
{
"text": "1 cup frozen peas, thawed",
"weight": 134
}
],
"calories": 4055.7632,
"totalWeight": 2765.59,
"totalTime": 60,
"totalNutrients": {},
"totalDaily": {},
"digest": []
},
"bookmarked": false,
"bought": false
},
{
"recipe": {
"uri": "http://www.edamam.com/ontologies/edamam.owl#recipe_8275bb28647abcedef0baaf2dcf34f8b",
"label": "Chicken Paprikash",
"image": "https://www.edamam.com/web-img/e12/e12b8c5581226d7639168f41d126f2ff.jpg",
"source": "No Recipes",
"url": "http://norecipes.com/recipe/chicken-paprikash/",
"shareAs": "http://www.edamam.com/recipe/chicken-paprikash-8275bb28647abcedef0baaf2dcf34f8b/chicken",
"yield": 4,
"dietLabels": [],
"healthLabels": [],
"cautions": [],
"ingredientLines": [],
"ingredients": [],
"calories": 3033.2012,
"totalWeight": 1824.6125,
"totalTime": 0,
"totalNutrients": {},
"totalDaily": {},
"digest": []
},
"bookmarked": false,
"bought": false
},
{
"recipe": {
"uri": "http://www.edamam.com/ontologies/edamam.owl#recipe_584ac5e486c088b3c8409c252d7f290c",
"label": "Chicken Gravy",
"image": "https://www.edamam.com/web-img/fd1/fd1afed1849c44f5185720394e363b4e.jpg",
"source": "Martha Stewart",
"url": "http://www.marthastewart.com/332664/chicken-gravy",
"shareAs": "http://www.edamam.com/recipe/chicken-gravy-584ac5e486c088b3c8409c252d7f290c/chicken",
"yield": 6,
"dietLabels": [],
"healthLabels": [],
"cautions": [],
"ingredientLines": [],
"ingredients": [],
"calories": 1092.3606,
"totalWeight": 1590.8628,
"totalTime": 270,
"totalNutrients": {},
"totalDaily": {},
"digest": []
},
"bookmarked": false,
"bought": false
},
{},
{},
{},
{},
{},
{},
{}
]
}
This is currently the method I am using to parse the JSON object:
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
final String myResponse = response.body().string();
getActivity().runOnUiThread(new Runnable() {
private Object Date;
#Override
public void run() {
String jsonData = myResponse;
query_result.setText(myResponse);
Log.d("response5", myResponse);
//JSONObject jsonData1 = new JSONObject(myResponse);
JSONObject Jobject = null;
try {
Jobject = new JSONObject(jsonData);
Log.d("jobject", Jobject.toString());
} catch (JSONException e) {
e.printStackTrace();
}
JSONArray Jarray = null;
try {
Jarray = Jobject.getJSONArray("hits");
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < Jarray.length(); i++) {
JSONObject object;
try {
object = Jarray.getJSONObject(i);
try {
JSONArray Recipe = object.getJSONArray("recipe");
}catch (JSONException e){
e.printStackTrace();
}
for (int j = 0; j < Jarray.length(); j++){
JSONObject object2 = null;
try {
object2 = Jarray.getJSONObject(j);
String Name = object2.getString("label");
String Photo = object2.getString("image");
Log.d("rec_query", " " + Photo);
}catch (JSONException e){
e.printStackTrace();
Log.d("response6:", e.toString());
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
}
}
});
return null;
}
}
NOTE THE {} {} are just different recipes...it wouldnt fit the whole response
At the moment, when I try to print my variables in the Log, I am getting a message that says the variable is empty (the variable that i used to store the different recipes/"hits".
Your response seems incomplete, it's not in the correct JSON format,Provide the right format and I'll try to help you
String s = "{\n" +
" \"a1\":\"1\",\n" +
" \"b2\":[\n" +
" {\n" +
" \"b21\":\"vb21\"\n" +
" },\n" +
" {\n" +
" \"b22\":\"vb22\"\n" +
" }\n" +
" ]\n" +
"}";
JSONObject object = JSON.parseObject(s);
String vb21 = object.getJSONArray("b2").getJSONObject(0).getString("b21");
like this,and neep to import com.alibaba.fastjson
But i dont`t know if you can use fastjson
I have multi Array key value string
For Example:
{
filters=[
{
eventConfig={
success=1.0,
bgColor=#27AE60,
successText=Yes
},
prid=9.0,
name=abc,
prqt=1.0,
price=199.89
},
{
eventConfig={
success=1.0,
bgColor=#27AE60,
successText=Yes
},
name=abc,
prid=10.0,
price=99.89,
prqt=1.0
},
{
eventConfig={
success=0.0,
bgColor=#C0392B,
successText=No
},
name=internet,
prid=11.0,
price=299.89,
prqt=1.0
},
{
eventConfig={
success=0.0,
bgColor=#C0392B,
successText=No
},
name=intermission,
prid=11.0,
price=299.89,
prqt=1.0
}
]
}
I'm trying to convert into json string but getting error while converting
i need output as
{
"filters": [
{
"eventConfig": {
"success": 1,
"bgColor": "#27AE60",
"successText": "Yes"
},
"prid": 9,
"name": "abc",
"prqt": 1,
"price": 199.89
},
{
"eventConfig": {
"success": 1,
"bgColor": "#27AE60",
"successText": "Yes"
},
"name": "abc",
"prid": 10,
"price": 99.89,
"prqt": 1
},
{
"eventConfig": {
"success": 0,
"bgColor": "#C0392B",
"successText": "No"
},
"name": "internet",
"prid": 11,
"price": 299.89,
"prqt": 1
},
{
"eventConfig": {
"success": 0,
"bgColor": "#C0392B",
"successText": "No"
},
"name": "intermission",
"prid": 11,
"price": 299.89,
"prqt": 1
}
]
}
Please use the following code snippet to Parse this response.
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray filtersArray = jsonObject.getJSONArray("filters");
for (int i = 0; i < filtersArray.length(); i++) {
//Parsing eventConfig object
JSONObject eventConfigObject = filtersArray.getJSONObject(i).getJSONObject("eventConfig");
int success = eventConfigObject.getInt("success");
String bgColor = eventConfigObject.getString("bgColor");
String successText = eventConfigObject.getString("successText");
//Parsing other objects
int prid = filtersArray.getJSONObject(i).getInt("prid");
String name = filtersArray.getJSONObject(i).getString("name");
int prqt = filtersArray.getJSONObject(i).getInt("prqt");
int price = filtersArray.getJSONObject(i).getInt("price");
}
} catch (Exception e) {
e.printStackTrace();
}
Happy Coding!! Thanks..!
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");
{
"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