Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 4 decodable json arrays

So I am currently woking on a program to parse a JSON Api which is linked at the bottom

When I run the code I get some output but not all image of console output

Mainly for the optional type of Anime which is good because it shows that it works but I also want to access the name and release date and languages however I have no idea how to work with JSON arrays like this in swift 4. I will attach my current code below.

import UIKit

struct AnimeJsonStuff: Decodable {
    let data: [AnimeDataArray]
}

struct AnimeDataArray: Decodable {
    let type: String?
}

class OsuHomeController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
    func jsonDecoding() {
        let jsonUrlString = "https://kitsu.io/api/edge/anime"

        guard let url = URL(string: jsonUrlString) else {return} //
        URLSession.shared.dataTask(with: url) { (data, response, err) in

            guard let data = data else {return}

            do {
                let animeJsonStuff =  try JSONDecoder().decode(AnimeJsonStuff.self, from: data)
                print(animeJsonStuff.data)

                let animeDataArray = try JSONDecoder().decode(AnimeDataArray.self, from: data)
                print(animeDataArray.type as Any)
            } catch let jsonErr {
                print("Error serializing json", jsonErr)
            }
        }.resume()
    }
}

I have more code after that but it's just for setting up custom collectionViewCells.

Also here is the link to the api

like image 420
Dengekiko Avatar asked Sep 24 '17 22:09

Dengekiko


1 Answers

Answer for title "Swift 4 decodable json arrays"

let decoder = JSONDecoder()
do {
   let array = try decoder.decode([YouCodableStruct].self, from: response.data!)
   debugPrint(array)
} catch {
   debugPrint("Error occurred")
}

http://andrewmarinov.com/parsing-json-swift-4/

like image 103
Neph Muw Avatar answered Oct 21 '22 07:10

Neph Muw