swiftalamofireswifty-json

Parsing JSON to a struct with SwiftyJSON


I have a simple struct to handle the data parsing from the SwiftyJSON

struct Threads{
    var threads:[ThreadDetail]
}

struct ThreadDetail {
    var title:String
    var username:String
    var prefix_id:Int
}

Here's a sample of the API response

{
    "threads": [
        {
            "first_post_id": 258535,
            "prefix_id": 1,
            "thread_id": 50204,
            "title": "Testing board title",
            "user_id": 20959,
            "username": "test",
            "view_count": 247,
        }

Now here's the part where I couldn't figure out how

        Alamofire.request(url, method: .get, headers: headers).validate().responseJSON { response in
            switch response.result {
            case .success(let value):
                let json = JSON(value)
                for item in json["threads"].arrayValue {

                    //how should it be written here?

                }
            case .failure(let error):
                print(error)
            }
        }
    }
}

Solution

  • Declare your models and conform them Codable.

    struct Response: Codable {
        let threads: [Thread]
    }
    
    // MARK: - Thread
    struct Thread: Codable {
        let firstPostID, prefixID, threadID: Int
        let title: String
        let userID: Int
        let username: String
        let viewCount: Int
    
        enum CodingKeys: String, CodingKey {
            case firstPostID = "first_post_id"
            case prefixID = "prefix_id"
            case threadID = "thread_id"
            case title
            case userID = "user_id"
            case username
            case viewCount = "view_count"
        }
    }
    

    After that, convert your data to model by using JSONDecoder

      Alamofire.request(urlString).response {
                response in
                guard let data = response.data else { return }
                do {
                    let decoder = JSONDecoder()
                    let threadsWrapper = try decoder.decode(Response.self, from: data)
                } catch let error {
                    print(error)
                }
    

    Use this website to convert your JSON to Codable https://app.quicktype.io/