简体   繁体   中英

E/Volley: com.android.volley.ParseError: org.json.JSONException: Value {"results":[{

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM