ios - 我在使用 JSON Decoder 时做错了什么

标签 ios json swift

我正在尝试解码 JSON,但是,我的断点直接进入 Catch 语句,而不是打印解码数据。我究竟做错了什么?我尝试的是创建另一个结构,在其中从 JSON 中解压所有数据数组,我已经在之前的项目中做到了这一点,但对于这个来说,其他东西是错误的。对于这个项目,我必须解析以下属性:

  • 姓名
  • ABV
  • 图片网址

JSON

[  
    {  
        "id":1,
        "name":"Buzz",
        "tagline":"A Real Bitter Experience.",
        "first_brewed":"09/2007",
        "description":"A light, crisp and bitter IPA brewed with English and American hops. A small batch brewed only once.",
        "image_url":"https://images.punkapi.com/v2/keg.png",
        "abv":4.5,
        "ibu":60,
        "target_fg":1010,
        "target_og":1044,
        "ebc":20,
        "srm":10,
        "ph":4.4,
        "attenuation_level":75,
        "volume":{  
            "value":20,
            "unit":"liters"
        },
        "boil_volume":{  
            "value":25,
            "unit":"liters"
        },
        "method":{  
            "mash_temp":[  
                {  
                    "temp":{  
                        "value":64,
                        "unit":"celsius"
                    },
                    "duration":75
                }
            ],
            "fermentation":{  
                "temp":{  
                    "value":19,
                    "unit":"celsius"
                }
            },
            "twist":null
        },
        "ingredients":{  
            "malt":[  
                {  
                    "name":"Maris Otter Extra Pale",
                    "amount":{  
                        "value":3.3,
                        "unit":"kilograms"
                    }
                },
                {  
                    "name":"Caramalt",
                    "amount":{  
                        "value":0.2,
                        "unit":"kilograms"
                    }
                },
                {  
                    "name":"Munich",
                    "amount":{  
                        "value":0.4,
                        "unit":"kilograms"
                    }
                }
            ],
            "hops":[  
                {  
                    "name":"Fuggles",
                    "amount":{  
                        "value":25,
                        "unit":"grams"
                    },
                    "add":"start",
                    "attribute":"bitter"
                },
                {  
                    "name":"First Gold",
                    "amount":{  
                        "value":25,
                        "unit":"grams"
                    },
                    "add":"start",
                    "attribute":"bitter"
                },
                {  
                    "name":"Fuggles",
                    "amount":{  
                        "value":37.5,
                        "unit":"grams"
                    },
                    "add":"middle",
                    "attribute":"flavour"
                },
                {  
                    "name":"First Gold",
                    "amount":{  
                        "value":37.5,
                        "unit":"grams"
                    },
                    "add":"middle",
                    "attribute":"flavour"
                },
                {  
                    "name":"Cascade",
                    "amount":{  
                        "value":37.5,
                        "unit":"grams"
                    },
                    "add":"end",
                    "attribute":"flavour"
                }
            ],
            "yeast":"Wyeast 1056 - American Ale™"
        },
        "food_pairing":[  
            "Spicy chicken tikka masala",
            "Grilled chicken quesadilla",
            "Caramel toffee cake"
        ],
        "brewers_tips":"The earthy and floral aromas from the hops can be overpowering. Drop a little Cascade in at the end of the boil to lift the profile with a bit of citrus.",
        "contributed_by":"Sam Mason <samjbmason>"
    },
    {  
        "id":2,
        "name":"Trashy Blonde",
        "tagline":"You Know You Shouldn't",
        "first_brewed":"04/2008",
        "description":"A titillating, neurotic, peroxide punk of a Pale Ale. Combining attitude, style, substance, and a little bit of low self esteem for good measure; what would your mother say? The seductive lure of the sassy passion fruit hop proves too much to resist. All that is even before we get onto the fact that there are no additives, preservatives, pasteurization or strings attached. All wrapped up with the customary BrewDog bite and imaginative twist.",
        "image_url":"https://images.punkapi.com/v2/2.png",
        "abv":4.1,
        "ibu":41.5,
        "target_fg":1010,
        "target_og":1041.7,
        "ebc":15,
        "srm":15,
        "ph":4.4,
        "attenuation_level":76,
        "volume":{  
            "value":20,
            "unit":"liters"
        },
        "boil_volume":{  
            "value":25,
            "unit":"liters"
        },
        "method":{  
            "mash_temp":[  
                {  
                    "temp":{  
                        "value":69,
                        "unit":"celsius"
                    },
                    "duration":null
                }
            ],
            "fermentation":{  
                "temp":{  
                    "value":18,
                    "unit":"celsius"
                }
            },
            "twist":null
        },
        "ingredients":{  
            "malt":[  
                {  
                    "name":"Maris Otter Extra Pale",
                    "amount":{  
                        "value":3.25,
                        "unit":"kilograms"
                    }
                },
                {  
                    "name":"Caramalt",
                    "amount":{  
                        "value":0.2,
                        "unit":"kilograms"
                    }
                },
                {  
                    "name":"Munich",
                    "amount":{  
                        "value":0.4,
                        "unit":"kilograms"
                    }
                }
            ],
            "hops":[  
                {  
                    "name":"Amarillo",
                    "amount":{  
                        "value":13.8,
                        "unit":"grams"
                    },
                    "add":"start",
                    "attribute":"bitter"
                },
                {  
                    "name":"Simcoe",
                    "amount":{  
                        "value":13.8,
                        "unit":"grams"
                    },
                    "add":"start",
                    "attribute":"bitter"
                },
                {  
                    "name":"Amarillo",
                    "amount":{  
                        "value":26.3,
                        "unit":"grams"
                    },
                    "add":"end",
                    "attribute":"flavour"
                },
                {  
                    "name":"Motueka",
                    "amount":{  
                        "value":18.8,
                        "unit":"grams"
                    },
                    "add":"end",
                    "attribute":"flavour"
                }
            ],
            "yeast":"Wyeast 1056 - American Ale™"
        },
        "food_pairing":[  
            "Fresh crab with lemon",
            "Garlic butter dipping sauce",
            "Goats cheese salad",
            "Creamy lemon bar doused in powdered sugar"
        ],
        "brewers_tips":"Be careful not to collect too much wort from the mash. Once the sugars are all washed out there are some very unpleasant grainy tasting compounds that can be extracted into the wort.",
        "contributed_by":"Sam Mason <samjbmason>"
    },

网络文件夹

import Foundation
import Alamofire
func getApiData(){
    guard let urlString = URL(string: "https://api.punkapi.com/v2/beers") else {
        print("URL Error")
        return
    }
    Alamofire.request(urlString).responseJSON { response in

        if response.data == response.data{
            do{
                let decoder = try JSONDecoder().decode(Data.self, from: response.data!)
                print(decoder)
            }catch{
        print(error)
            }
        }else{print("API Response is Empty")}

        }
}

模型文件夹

import Foundation

struct Data:Decodable {
    let cervejas : [Cerveja]
}

struct Cerveja:Decodable{
    let name:String?
    let abv:String?
    let image_url:String?
}

最佳答案

尝试使用

let models = try JSONDecoder().decode([Cerveja].self, from: response.data!)

Cerveja 类更改为

let abv:Double?

成功解码后访问它们就像

for model in models {
    print(model.name)
}

关于ios - 我在使用 JSON Decoder 时做错了什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51385316/

相关文章:

ios - watchOS 2 - 如何随机选择 UIButtons

objective-c - 将父类的实例转换为其子类

ios - xcode - 无效的位码

ios - 无法使用 HTTP 请求发布到 php,但代码中没有错误

ios - UICollectionView 滚动非常不稳定

ios - 推送通知时如何在 ViewController 上执行操作并检索其数据

ios - 如何使用解析框架在iOS中使用连接查询?

json - Express:阻止bodyParser解析请求

java - 如何使用任何 json 库/jar 构造 json 对象

javascript - 将 json 扁平化为 csv 格式