'Parse nested value from JSON and add into HashMap

I am using data from the Yummly API to get recipe details. I am creating an Android app which will display recipes based on a matching ingredient the user has entered. I am trying to get to the "recipeName" tag but it's complaining that there is no value for it and I have tried various approaches. I'm trying to add all the recipe names into a HashMap, which will be displayed in a ListView later on.

Below is an example of one recipe (out of 39) that comes in the form of a JSON Object.

Click here for full response

{
    "attribution": {
        "html": "<a href='http://www.yummly.com/recipes/soup'>soup recipes</a> search powered by <img src=''/>",
        "url": "http://www.yummly.com/recipes/soup",
        "text": "soup recipes: search powered by Yummly",
        "logo": ""
    },
    "totalMatchCount": 39,
    "facetCounts": {},
    "matches": [
        {
            "attributes": {
                "course": [
                    "Soups"
                ],
                "cuisine": [
                    "Italian"
                ]
            },
            "flavors": {
                "salty": 0.6666666666666666,
                "sour": 0.8333333333333334,
                "sweet": 0.6666666666666666,
                "bitter": 0.5,
                "meaty": 0.16666666666666666,
                "piquant": 0.5
            },
            "rating": 4.6,
            "id": "Vegetarian-Cabbage-Soup-Recipezaar",
            "smallImageUrls": [],
            "sourceDisplayName": "Food.com",
            "totalTimeInSeconds": 4500,
            "ingredients": [
                "garlic cloves",
                "ground pepper",
                "diced tomatoes",
                "celery",
                "tomato juice",
                "salt",
                "cabbage",
                "bell peppers",
                "oregano",
                "carrots",
                "basil",
                "vegetable broth",
                "chili pepper flakes",
                "green beans",
                "onions",
                "onion soup mix"
            ],
            "recipeName": "Vegetarian Cabbage Soup"
        }
}

Fragment of my Search class

//imports above  

    private static final String TAG_TOTAL_MATCH = "totalMatchCount";
    private static final String TAG_MATCHES = "matches";
    private static final String TAG_NAME = "recipeName";
    private static final String TAG_RATING = "rating";

        JSONParser jsonParser = new JSONParser();

        protected String doInBackground(String... args) {    
            JSONObject json = jsonParser.makeHttpRequest(full_url, "GET", params);

            // check log cat for JSON response
            Log.d("Response", json.toString());

            // check for success tag
            try {
                int count = json.getInt(TAG_TOTAL_MATCH);
                String name = json.getString(TAG_NAME);
                String matches = json.getString(TAG_MATCHES);
                JSONObject namelist = json.getJSONObject(matches).getJSONObject(name);

                HashMap<String, String> pairs = new HashMap<String, String>();

                if (count > 0) {
                    int i;

                    //populate Hashmap with recipe names
                    for (i=1; i<=count; i++){
                        Iterator it = namelist.keys();
                        while (it.hasNext()) {
                            String n = (String) it.next();
                            pairs.put(n,name);
                        }
                    }
                    //display Hashmap in terminal
                    for(int j =0; j<pairs.size(); j++) {
                        System.out.println(pairs.get(j));

                }

            }
        }
    }

I didn't include everything since it's not relevant. Log.d() does give me a JSON object much like the one displayed at the top of this question so the JSON is successfully parsed, it's just Android studio says there is no value for "recipeName". What am I doing wrong?



Solution 1:[1]

recipeName and rating are inside matches, but you're trying to access them as if they're at the same level as totalMatchCount.

As a start, consider removing this line:

String matches = json.getString(TAG_MATCHES);

And change the next line to grab the matches array from the root object:

JSONArray matches = json.getJSONArray(TAG_MATCHES);

I'm sure you can take it from there by iterating over the matches array and dealing with each recipe independently.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Doug Stevenson