-3

I can't get the JSON data of the link it always get the error. "Expected to decode Array<Any> but found a dictionary instead." Thank you.

My 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: ""
}]

My Struct

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 function

  // 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()
}
vadian
  • 274,689
  • 30
  • 353
  • 361
Guren
  • 182
  • 2
  • 14

1 Answers1

1

You are saying decode([Root].self..., as if your JSON were an array of Root. But it is not an array of Root. It is a Root. Say decode(Root.self.

Then change

for info in articles

To

for info in articles.server_response

That is the array.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • if I remove the array on ` Root.self ` I get this error in for `Type 'Root' does not conform to protocol 'Sequence` – Guren Nov 10 '18 at 03:48
  • Your comment is about a totally different mistake where you say `for info in articles`. That is wrong too. But it has nothing to do with what you asked! For what you asked my answer is right. – matt Nov 10 '18 at 03:53