[java] How to Get JSON Array Within JSON Object?

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?

This question is related to java android json

The answer is


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"));
                }


       }

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 
   }
}

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 guess this will help you.

JSONObject jsonObj = new JSONObject(jsonStr);

JSONArray ja_data = jsonObj.getJSONArray("data");
int length = jsonObj.length();
for(int i=0; i<length; i++) {
  JSONObject jsonObj = ja_data.getJSONObject(i);
  Toast.makeText(this, jsonObj.getString("Name"), Toast.LENGTH_LONG).show();

  // getting inner array Ingredients
  JSONArray ja = jsonObj.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"));
  }
}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?