0

I am trying to get data from a JSON from the Spoonacular API and display it is a list on a RecyclerView. However, I keep getting the error below when running the program.

I have created a Meal class to get and set the information from the JSON file and the JSON file works when searched in google.

Is there something not correct in my code or am I missing something in my code? Any help would be appreciated. Thanks

The error:

E/Volley: com.android.volley.ParseError: org.json.JSONException: Value {"results":[{"vegetarian":true,"vegan":true,"glutenFree":true,"dairyFree":true,"veryHealthy":true,.......}

The full stack trace error:

2020-02-20 15:58:09.045 19600-19600/com.example.apitest E/Volley: com.android.volley.ParseError: org.json.JSONException: Value {"results":[{"vegetarian":true,"vegan":true,"glutenFree":true,"dairyFree":true,"veryHealthy":true,"cheap":false,"veryPopular":true,"sustainable":false,"weightWatcherSmartPoints":9,"gaps":"no","lowFodmap":false,"preparationMinutes":0,"cookingMinutes":15,"sourceUrl":"http:\/\/www.eatingwell.com\/recipe\/251410\/baby-kale-breakfast-salad-with-quinoa-strawberries\/","spoonacularSourceUrl":"https:\/\/spoonacular.com\/baby-kale-breakfast-salad-with-quinoa-strawberries-955591","aggregateLikes":462,"spoonacularScore":100,"healthScore":100,"creditsText":"Eating Well","sourceName":"Eating Well","pricePerServing":226.2,"id":955591,"title":"Baby Kale Breakfast Salad with Quinoa & Strawberries","readyInMinutes":15,"servings":1,"image":"https:\/\/spoonacular.com\/recipeImages\/955591-312x231.jpg","imageType":"jpg","cuisines":[],"dishTypes":["morning meal","brunch","breakfast"],"diets":["gluten free","dairy free","lacto ovo vegetarian","vegan"],"occasions":[],"winePairing":{},"analyzedInstructions":[{"name":"","steps":[{"number":1,"step":"Mash garlic and salt together with the side of a chef's knife or a fork to form a paste.","ingredients":[{"id":11215,"name":"garlic","image":"garlic.png"},{"id":2047,"name":"salt","image":"salt.jpg"}],"equipment":[{"id":404672,"name":"chefs knife","image":"chefs-knife.jpg"}]},{"number":2,"step":"Whisk the garlic paste, oil, vinegar and pepper together in a medium bowl.","ingredients":[{"id":10111215,"name":"garlic paste","image":"garlic-paste.png"},{"id":1002030,"name":"pepper","image":"pepper.jpg"}],"equipment":[{"id":404661,"name":"whisk","image":"whisk.png"},{"id":404783,"name":"bowl","image":"bowl.jpg"}]},{"number":3,"step":"Add kale; toss to coat.","ingredients":[{"id":11233,"name":"kale","image":"kale.jpg"}],"equipment":[]},{"number":4,"step":"Serve topped with quinoa, strawberries and pepitas.","ingredients":[{"id":9316,"name":"strawberries","image":"strawberries.png"},{"id":12014,"name":"pumpkin seeds","image":"pumpkin-seeds.jpg"}],"equipment":[]}]}],"nutrition":[{"title":"Calories","amount":418.811,"unit":"cal"}]},{"vegetarian":false,"vegan":false,"glutenFree":true,"dairyFree":true,"veryHealthy":true,"cheap":false,"veryPopular":true,"sustainable":false,"weightWatcherSmartPoints":5,"gaps":"no","lowFodmap":true,"preparationMinutes":1,"cookingMinutes":2,"sourceUrl":"http:\/\/www.sugarfreemom.com\/recipes\/oatmeal-berry-breakfast-cake-dairy-gluten-sugar-free\/","spoonacularSourceUrl":"https:\/\/spoonacular.com\/oatmeal-berry-breakfast-cake-dairy-gluten-sugar-free-557456","aggregateLikes":1189,"spoonacularScore":100,"healthScore":77,"creditsText":"Sugar Free Mom","sourceName":"Sugar Free Mom","pricePerServing":215.49,"id":557456,"title":"Oatmeal Berry Breakfast Cake ","readyInMinutes":3,"servings":1,"image":"https:\/\/spoonacular.com\/recipeImages\/557456-312x231.jpg","imageType":"jpg","cuisines":[],"dishTypes":["morning meal","brunch","breakfast"],"diets":["gluten free","dairy free","fodmap friendly"],"occasions":[],"winePairing":{},"analyzedInstructions":[{"name":"","steps":[{"number":1,"step":"Spray a large 16 ounce ramekin (or use two small ramekins) with nonstick cooking spray.","ingredients":[],"equipment":[{"id":404781,"name":"ramekin","image":"ramekin.jpg"}]},{"number":2,"step":"Mix all ingredients together in the ramekin except the berries.Stir well to incorporate,","ingredients":[],"equipment":[{"id":404781,"name":"ramekin","image":"ramekin.jpg"}]},{"number":3,"step":"Add berries.Save a few for topping if desired. Microwave for 3 minutes until puffed and no longer liquid-y in center.Or bake at 350 degrees for 25-30 minutes.","ingredients":[],"equipment":[{"id":404762,"name":"microwave","image":"microwave.jpg"}],"length":{"number":33,"unit":"minutes"}},{"number":4,"step":"Serve warm with additional toppings.","ingredients":[],"equipment":[]}]}],"nutrition":[{"title":"Calories","amount":269.785,"unit":"cal"}]},{"vegetarian":false,"vegan":false,"glutenFree":true,"dairyFree":true,"veryHealthy":t

The code:

private void getData() {
    final ProgressDialog progressDialog = new ProgressDialog(this);
    progressDialog.setMessage("Loading...");
    progressDialog.show();

    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(URL_MEAL, new Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray response) {
            for (int i = 0; i < response.length(); i++) {
                try {
                    JSONObject jsonObject = response.getJSONObject(i);
                    JSONArray array = jsonObject.getJSONArray("results");

                    Meal meal = new Meal();
                    meal.setMealTitle(jsonObject.getString("title"));
                    meal.setDiets(jsonObject.getString("diets"));
                    meal.setImage(jsonObject.getString("image"));

                    JSONArray childrenArray = jsonObject.getJSONArray("nutrition");
                    meal.setCalorieAmount(jsonObject.getInt("amount"));

                    meals.add(meal);
                } catch (JSONException e) {
                    e.printStackTrace();
                    progressDialog.dismiss();
                }
            }
            adapter.notifyDataSetChanged();
            progressDialog.dismiss();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("Volley", error.toString());
            progressDialog.dismiss();
        }
    });
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(jsonArrayRequest);
}
dmcm
  • 1
  • 2
  • Please post the full stacktrace and one more thing Looking this line `JSONArray array = jsonObject.getJSONArray("results");` i am guessing your result object is a JSONArray and you have iterate over your json array to get the values other wise please post the sample json string which you are getting – Seshidhar G Feb 20 '20 at 15:51
  • Hi, yes the result object is a JSON Array and I am getting the information out of the results array. There are also multiple arrays inside the "results" array so I don't know if that is to do with the problem? – dmcm Feb 20 '20 at 16:00
  • I have edited the questions with the full stack trace error above – dmcm Feb 20 '20 at 16:02
  • @SeshidharG the sample JSON string can be seen in the error from the Stack Trace – dmcm Feb 20 '20 at 16:10

1 Answers1

0

It is a complex json and to get the values you have to change your onResponse method Here i tried to improvise your method.

public void onResponse(JSONArray response) {
    for (int i = 0; i < response.length(); i++) {
        try {
            JSONObject jsonObject = response.getJSONObject(i);
            JSONArray array = jsonObject.getJSONArray("results");
            //now you have iterate over jsonArray to get the values
            for (int j = 0; j < array.length(); j++) {
                //json array contains multiple json objects 
                JSONObject objects = array.getJSONObject(i);

                // printing...
                System.out.println(objects.getString("title"));
                System.out.println(objects.getString("diets"));
                System.out.println(objects.getString("image"));
                System.out.println(objects.getJSONArray("nutrition").getJSONObject(0).getInt("amount"));

                // output for the above system outs
                //Baby Kale Breakfast Salad with Quinoa & Strawberries
                //["gluten free","dairy free","lacto ovo vegetarian","vegan"]
                //https://spoonacular.com/recipeImages/955591-312x231.jpg
                //418


                Meal meal = new Meal();
                meal.setMealTitle(objects.getString("title"));
                // objects.getString("diets") this is again a json array.
                meal.setDiets(objects.getString("diets"));
                meal.setImage(objects.getString("image"));

                meal.setCalorieAmount(objects.getJSONArray("nutrition").getJSONObject(0).getInt("amount"));
                meals.add(meal);
            }

        } catch (JSONException e) {
            e.printStackTrace();
            progressDialog.dismiss();
        }

try this and let me know if you are looking any thing else Happy coding...

Seshidhar G
  • 265
  • 1
  • 9
  • Hi @SeshidharG I tried changing my onResponse method to be the same as the code you provided however the error still seems to appear. Is it something to do with the way I am calling the JSON or is there another problem somewhere else? – dmcm Feb 22 '20 at 23:34