E / Volley: com. android .volley.ParseError: org. json .JSONException: Value {"results": [{ - PullRequest
0 голосов
/ 20 февраля 2020

Я пытаюсь получить данные из JSON из API Spoonacular и отобразить их в виде списка в RecyclerView. Тем не менее, я получаю сообщение об ошибке ниже при запуске программы.

Я создал класс Meal для получения и установки информации из файла JSON, и файл JSON работает при поиске в Google.

Что-то не так в моем коде или я что-то упустил в моем коде? Любая помощь будет оценена. Спасибо

Ошибка:

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

Ошибка трассировки полного стека:

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

Код:

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

1 Ответ

0 голосов
/ 21 февраля 2020

Это сложный json, и чтобы получить значения, вы должны изменить свой onResponse метод. Здесь я попытался импровизировать ваш метод.

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

попробуйте это и позвольте мне знаю, если вы ищете что-нибудь еще Счастливое кодирование ...

...