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..!
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!
This question already has answers here:
Parsing JSON File Java [duplicate]
(7 answers)
Closed 5 years ago.
I need to get the corresponding "value" based on the "attr_id" from "full_nutrients" array in the JSON response below using Java, how can this be accomplished? For example I want to get the value when "attr_id" == 205.
JSON Response:
"foods": [
{
"food_name": "chicken noodle soup",
"brand_name": null,
"serving_qty": 1,
"serving_unit": "cup",
"serving_weight_grams": 248,
"nf_calories": 62,
"nf_total_fat": 2.36,
"nf_saturated_fat": 0.65,
"nf_cholesterol": 12.4,
"nf_sodium": 865.52,
"nf_total_carbohydrate": 7.32,
"nf_dietary_fiber": 0.5,
"nf_sugars": 0.67,
"nf_protein": 3.15,
"nf_potassium": 54.56,
"nf_p": 42.16,
"full_nutrients": [
{
"attr_id": 203,
"value": 3.1496
},
{
"attr_id": 204,
"value": 2.356
},
{
"attr_id": 205,
"value": 7.316
},
{
"attr_id": 207,
"value": 2.5048
}],
}
Your json is invalid .
You can change to this .
{"foods": [
{
"food_name": "chicken noodle soup",
"brand_name": null,
"serving_qty": 1,
"serving_unit": "cup",
"serving_weight_grams": 248,
"nf_calories": 62,
"nf_total_fat": 2.36,
"nf_saturated_fat": 0.65,
"nf_cholesterol": 12.4,
"nf_sodium": 865.52,
"nf_total_carbohydrate": 7.32,
"nf_dietary_fiber": 0.5,
"nf_sugars": 0.67,
"nf_protein": 3.15,
"nf_potassium": 54.56,
"nf_p": 42.16,
"full_nutrients": [
{
"attr_id": 203,
"value": 3.1496
},
{
"attr_id": 204,
"value": 2.356
},
{
"attr_id": 205,
"value": 7.316
},
{
"attr_id": 207,
"value": 2.5048
}],
}
}
Try this
try {
// if your response is { },you can use JSONObject
JSONObject jsonObject = new JSONObject(response);
// then find the foods tag in your json data
JSONArray foods = jsonObject.getJSONArray("foods");
// loop for the JSONArray
for (int i = 0; i < foods.length(); i++) {
// getJSONObject from the index
JSONObject jsonObject1 = foods.getJSONObject(i);
// then get full_nutrients tag
JSONArray full_nutrients = jsonObject1.getJSONArray("full_nutrients");
// loop for the JSONArray
for (int j = 0; j < full_nutrients.length(); j++) {
// getJSONObject from the index again
JSONObject jsonObject2 = full_nutrients.getJSONObject(i);
// get attr_id
String attr_id = jsonObject2.getString("attr_id");
// get value
String value = jsonObject2.getString("value");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Try this:
function Double GetValue(String json_object, int attr_id) {
Double tResult = 0;
JSONObject reader = new JSONObject(json_object);
// Getting JSON Array node
JSONArray full_nutrients = reader.getJSONArray("full_nutrients");
// looping through All full_nutrients
for (int i = 0; i < full_nutrients.length(); i++) {
JSONObject c = full_nutrients.getJSONObject(i);
if (c.getInt("attr_id") == attr_id)
tResult = c.getDouble("value");
}
return tResult;
}
How can i parse json like this:
{"SizeOptions": [
{
"Name": "دور باسن",
"GroupSizeId": 2,
"Id": 5,
"LangId": 0
},
{
"Name": "دور کمر",
"GroupSizeId": 2,
"Id": 6,
"LangId": 0
} ],"SizeValues": [
{
"Value": "a",
"SizeId": 11,
"SizeOptionId": 5,
"ProductId": 1069,
"Id": 145627,
"LangId": 0
},
{
"Value": "a",
"SizeId": 11,
"SizeOptionId": 8,
"ProductId": 1069,
"Id": 145630,
"LangId": 0
} ],"Sizes": [
{
"Name": "XXL",
"GroupSizeId": 2,
"Id": 11,
"LangId": 0
},
{
"Name": "L",
"GroupSizeId": 2,
"Id": 12,
"LangId": 0
}]}
I want to put all of Names in "SizeOptions" in diffrent Strings(String name1,name2,name3)
i tried this for getting started :
JSONObject jObject = new JSONObject(response);
JSONObject p = jObject.getJSONObject("SizeOptions");
String name = p.getString("Name");
but it's just giving me a "Null" value!
what's its problem? how can i fix it? Please Help
JSONObject jObject = new JSONObject(response);
JSONSONArray p = jObject.getJSONArray("SizeOptions");
for(int i=0;i<p.length();i++)
{
JSONObject jObjectValue=p.getJSONObject(i);
String name = jObjectValue.getString("Name");
}
You are trying to get a JSONArray as JSONObject. Try the following:
JSONObject jObject = new JSONObject(response);
List<String> names = new ArrayList<>();
JSONArray p = jObject.getJSONArray("SizeOptions");
for (int i = 0; i < p.length(); i++) {
JSONObject jo = p.getJSONObject(i);
String name = jo.getString("Name");
names.add(name);
}
System.out.println(names);
{
"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
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();
}
}