简体   繁体   English

从JSON解析嵌套的值并添加到HashMap中

[英]Parse nested value from JSON and add into HashMap

I am using data from the Yummly API to get recipe details. 我正在使用Yummly API中的数据来获取食谱详细信息。 I am creating an Android app which will display recipes based on a matching ingredient the user has entered. 我正在创建一个Android应用程序,该应用程序将根据用户输入的匹配成分显示食谱。 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. 我正在尝试使用“ recipeName”标签,但它抱怨它没有任何价值,因此我尝试了各种方法。 I'm trying to add all the recipe names into a HashMap, which will be displayed in a ListView later on. 我正在尝试将所有配方名称添加到HashMap中,该名称稍后将显示在ListView中。

Below is an example of one recipe (out of 39) that comes in the form of a JSON Object. 以下是一个以JSON对象形式提供的食谱(共39个)的示例。

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". Log.d()确实给了我一个JSON对象,就像该问题顶部显示的那样,因此JSON已成功解析,只是Android Studio表示“ recipeName”没有任何价值。 What am I doing wrong? 我究竟做错了什么?

recipeName and rating are inside matches , but you're trying to access them as if they're at the same level as totalMatchCount . recipeNamerating在内部matches ,但是您尝试访问它们就像它们与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: 并更改下一行以从根对象中获取matchs数组:

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. 我确信您可以通过遍历matchs数组并独立处理每个配方来从那里获取它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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