简体   繁体   English

API 解码结构 Swift

[英]API Decoding Struct Swift

在此处输入图像描述 在此处输入图像描述 Hello I'm trying to decode this API, https://gorest.co.in/public-api/posts .您好,我正在尝试解码此 API, https://gorest.co.in/public-api/posts What I'm doing wrong with structs?我在结构上做错了什么? Thank you.谢谢你。

struct Root: Decodable {
let first: [Code]
let second: [Meta]
let third: [Post] } 

struct Code: Decodable {
    let code: Int
}

struct Meta: Decodable {
    let meta: [Pagination]
}

struct Pagination: Decodable {
    let total: Int
    let pages: Int
    let page: Int
    let limit: Int
}

struct Post: Decodable {
    let id: Int
    let user_id: Int
    let title: String
    let body: String
}

Quicktype.io is your friend. Quicktype.io是您的朋友。 Post the JSON to it and get the struct back automatically.将 JSON 发布到它并自动获取结构。

// This file was generated from JSON Schema using quicktype, do not modify it directly.
// To parse the JSON, add this file to your project and do:
//
//   let root = try? newJSONDecoder().decode(Root.self, from: jsonData)

import Foundation

// MARK: - Root
struct Root: Codable {
    let code: Int
    let meta: Meta
    let data: [Datum]
}

// MARK: - Datum
struct Datum: Codable {
    let id, userID: Int
    let title, body: String

    enum CodingKeys: String, CodingKey {
        case id
        case userID = "user_id"
        case title, body
    }
}

// MARK: - Meta
struct Meta: Codable {
    let pagination: Pagination
}

// MARK: - Pagination
struct Pagination: Codable {
    let total, pages, page, limit: Int
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM