使用JSONDecoder后如何正确调用属性

时间:2018-07-17 17:25:13

标签: ios json swift

我正在解码JSON,然后创建了completeHandler函数,以便能够在项目中的任何位置获取JSON解析的属性。但是,当我调用该函数并仅打印所需的属性时,我将它们全部合并在一起,而不是调用了该属性。

例如:我叫beer.name,所以当我打印出来时,我得到了解码的Struct中包含的所有属性和值。我究竟做错了什么?我需要将这些值分开以能够填充UITableView以及其他组件。

ViewController

 override func viewDidLoad() {
        super.viewDidLoad()

        getApiData { (cerveja) in
            for beer in cerveja {
                print(beer.name!)
            } 
        }
    }
  

这就是我在下面的通话中所得到的:

[HakerRank___Bruno_Vavretchek.Cerveja(name: Optional("Buzz"), abv: 4.5, image_url: "https://images.punkapi.com/v2/keg.png"), HakerRank___Bruno_Vavretchek.Cerveja(name: Optional("Trashy Blonde"), abv: 4.1, image_url: "https://images.punkapi.com/v2/2.png"), HakerRank___Bruno_Vavretchek.Cerveja(name: Optional("Berliner Weisse With Yuzu - B-Sides"), abv: 4.2, image_url: "https://images.punkapi.com/v2/keg.png"), HakerRank___Bruno_Vavretchek.Cerveja(name: Optional("Pilsen Lager"), abv: 6.3, image_url: "https://images.punkapi.com/v2/4.png"), HakerRank___Bruno_Vavretchek.Cerveja(name: Optional("Avery Brown Dredge"), abv: 7.2, image_url: "https://images.punkapi.com/v2/5.png"), HakerRank___Bruno_Vavretchek.Cerveja(name: Optional("Electric India"), abv: 5.2, image_url: "https://images.punkapi.com/v2/6.png"), HakerRank___Bruno_Vavretchek.Cerveja(name: Optional("AB:12"), abv: 11.2, image_url: "https://images.punkapi.com/v2/7.png"), HakerRank___Bruno_Vavretchek.Cerveja(name: Optional("Fake Lager"), abv: 4.7, image_url: "https://images.punkapi.com/v2/8.png"), HakerRank___Bruno_Vavretchek.Cerveja(name: Optional("AB:07"), abv: 12.5, image_url: "https://images.punkapi.com/v2/9.png"), HakerRank___Bruno_Vavretchek.Cerveja(name: Optional("Bramling X"), abv: 7.5, image_url: "https://images.punkapi.com/v2/10.png"), HakerRank___Bruno_Vavretchek.Cerveja(name: Optional("Misspent Youth"), abv: 7.3, image_url: "https://images.punkapi.com/v2/keg.png"), HakerRank___Bruno_Vavretchek.Cerveja(name: Optional("Arcade Nation"), abv: 5.3, image_url: "https://images.punkapi.com/v2/12.png"), HakerRank___Bruno_Vavretchek.Cerveja(name: Optional("Movember"), abv: 4.5, image_url: "https://images.punkapi.com/v2/13.png"), HakerRank___Bruno_Vavretchek.Cerveja(name: Optional("Alpha Dog"), abv: 4.5, image_url: "https://images.punkapi.com/v2/14.png"), HakerRank___Bruno_Vavretchek.Cerveja(name: Optional("Mixtape 8"), abv: 14.5, image_url: "https://images.punkapi.com/v2/15.png"), HakerRank___Bruno_Vavretchek.Cerveja(name: Optional("Libertine Porter"), abv: 6.1, image_url: "https://images.punkapi.com/v2/16.png"), HakerRank___Bruno_Vavretchek.Cerveja(name: Optional("AB:06"), abv: 11.2, image_url: "https://images.punkapi.com/v2/17.png"), HakerRank___Bruno_Vavretchek.Cerveja(name: Optional("Russian Doll – India Pale Ale"), abv: 6.0, image_url: "https://images.punkapi.com/v2/18.png"), HakerRank___Bruno_Vavretchek.Cerveja(name: Optional("Hello My Name Is Mette-Marit"), abv: 8.2, image_url: "https://images.punkapi.com/v2/19.png"), HakerRank___Bruno_Vavretchek.Cerveja(name: Optional("Rabiator"), abv: 10.27, image_url: "https://images.punkapi.com/v2/keg.png"), HakerRank___Bruno_Vavretchek.Cerveja(name: Optional("Vice Bier"), abv: 4.3, image_url: "https://images.punkapi.com/v2/keg.png"), HakerRank___Bruno_Vavretchek.Cerveja(name: Optional("Devine Rebel (w/ Mikkeller)"), abv: 12.5, image_url: "https://images.punkapi.com/v2/22.png"), HakerRank___Bruno_Vavretchek.Cerveja(name: Optional("Storm"), abv: 8.0, image_url: "https://images.punkapi.com/v2/23.png"), HakerRank___Bruno_Vavretchek.Cerveja(name: Optional("The End Of History"), abv: 55.0, image_url: "https://images.punkapi.com/v2/24.png"), HakerRank___Bruno_Vavretchek.Cerveja(name: Optional("Bad Pixie"), abv: 4.7, image_url: "https://images.punkapi.com/v2/25.png")]

我真正需要的是所有名称或abv或image_url的

模型文件夹:

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

网络文件夹:

func getApiData(completion: @escaping ([Cerveja]) -> ()){
    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([Cerveja].self, from: response.data!)
                print(decoder)
            }catch{
        print(error)
            }
        }else{print("API Response is Empty")}

        }
}

3 个答案:

答案 0 :(得分:0)

您当前的附件日志来自

print(decoder)

不是来自for循环,请对其进行注释并尝试,您甚至不返回完成情况

func getApiData(completion: @escaping ([Cerveja]) -> ()){
    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([Cerveja].self, from: response.data!)
               // print(decoder)

                completion(decoder) // here 

            }
            catch{
                 print(error)
            }
        }else{print("API Response is Empty")}

        }
}

答案 1 :(得分:0)

实际上,您正在打印“解码器”。您必须这样写:

func getApiData(completion: @escaping ([Cerveja]) -> ()){
guard let urlString = URL(string: "https://api.punkapi.com/v2/beers") else {
    print("URL Error")
    return
}
Alamofire.request(urlString).responseJSON { response in

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

    }

}

避免强行打开包装。因此,使用

if let data = response.data{ 
   // Some code
}

然后您可以在viewDidLoad()中打印它

 override func viewDidLoad() {
    super.viewDidLoad()

    getApiData { (cerveja) in
        for beer in cerveja {
            print(beer.name!)
        } 
    }
}

答案 2 :(得分:0)

创建模型数组>

// re-indexing $datalist since in your example it is not 0-indexed
$datalist = array_values($datalist);
foreach ($response->monitors as $index=>$monitors) {
    if(isset($monitors->id)){
        echo
            '<tr>
             <td><i class="fas fa-globe"></i> '.$monitors->friendly_name.'</td>';
        echo '<td>'.$datalist[$index][2].'</td>';

        echo '<td>'.$monitors->url.'</td>
            <td>'.$monitors->status.'</td>
            </tr>';
    }
}

现在准备使用控制器并在tableView单元中使用。

 var arrBeer: [Cerveja]()

 override func viewDidLoad() {
    super.viewDidLoad()

    getApiData { (cerveja) in

     arrBeer = cerveja // you save all your model objects in this array
    }
}

希望这对您有所帮助。