簡體   English   中英

無法解析數組 JSON 解碼器 Swift 4

[英]Can't Parse Array JSON Decoder Swift 4

我無法獲取鏈接的 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

    }

我的從數據服務器提取功能

  // 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()
}

你說的是decode([Root].self... ,就好像你的 JSON 是一個 Root 數組。但它不是一個 Root 數組。它是一個 Root。說decode(Root.self

然后改變

for info in articles

for info in articles.server_response

那就是數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM