【问题标题】:Can't Parse Array JSON Decoder Swift 4无法解析数组 JSON 解码器 Swift 4
【发布时间】:2018-11-10 03:30:01
【问题描述】:

我无法获取链接的 JSON 数据,它总是出错。 "Expected to decode Array<Any> but found a dictionary instead."谢谢。

我的 JSON

{
server_response: [
{
id: "1",
magazine_title: "Volume 1 Issue 1",
mobile_link: "",
magazine_img: "https://www.pcbuyersguide.com.ph/wp-content/uploads/magazine_cover/pcbg.png",
mobile_zip: ""
},
{
id: "2",
magazine_title: "Volume 1 Issue 2",
mobile_link: "",
magazine_img: "https://www.pcbuyersguide.com.ph/wp-content/uploads/magazine_cover/pcbg.png",
mobile_zip: ""
},
{
id: "3",
magazine_title: "Volume 1 Issue 4",
mobile_link: "",
magazine_img: "https://www.pcbuyersguide.com.ph/wp-content/uploads/magazine_cover/pcbg.png",
mobile_zip: ""
},
{
id: "4",
magazine_title: "Volume 2 Issue 1",
mobile_link: "",
magazine_img: "https://www.pcbuyersguide.com.ph/wp-content/uploads/magazine_cover/pcbg.png",
mobile_zip: ""
}]

我的结构

struct Root: Decodable{

       var server_response: [server_details]
    }

    struct server_details: Decodable{

        var  magazine_title : String
        var magazine_img : String
        var mobile_link: String

    }

My Fetch from data server 功能

  // FETCH MAGAZINE
func fetchDatafromServer(){

    guard let url = URL(string: "https://www.pcbuyersguide.com.ph/wp-content/mobileapp/pcbg_magazine_data.php") else {return}
    URLSession.shared.dataTask(with: url) { (data, res, err) in

        guard let data = data else {return}

        do{
            let articles = try JSONDecoder().decode([Root].self, from: data)

            for info in articles {

                self.magazine_title.append(info.server_response[1].magazine_title)


            }

            DispatchQueue.main.async {

                self.collectionView?.reloadData()
            }
        }
        catch let jsonErr{

            print(jsonErr)
        }

        }.resume()
}

【问题讨论】:

    标签: ios json swift jsondecoder


    【解决方案1】:

    您在说decode([Root].self...,就好像您的 JSON 是一个 Root 数组。但它不是 Root 的数组。它是一个根。说decode(Root.self。

    然后改变

    for info in articles
    

    到

    for info in articles.server_response
    

    那是数组。

    【讨论】:

    • 如果我删除 `Root.self` 上的数组,Type 'Root' does not conform to protocol 'Sequence 会出现此错误
    • 你的评论是关于一个完全不同的错误,你说for info in articles。那也是错误的。但这与你问的无关!你问我的答案是对的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-31
    • 1970-01-01
    相关资源
    最近更新 更多