【问题标题】:Swift Codable Json ResponseSwift 可编码 Json 响应
【发布时间】:2020-03-26 15:58:58
【问题描述】:

我有以下来自 API 的 JSON 响应,

{
    "status_code": 1000,
    "data": [
        {
            "id": 3,
            "invoice_id": 100000,
            "user_id": 1000,
            "contact_number": "NA",
            "province": 0,
            "location": "100000",
            "total": 0,
            "confirm_code": 1234,
            "status": 0,
            "created_at": "2020-03-18 22:07:25",
            "updated_at": "2020-03-18 22:07:25"
        },
        {
            "id": 4,
            "invoice_id": 100000,
            "user_id": 1000,
            "contact_number": "NA",
            "province": 0,
            "location": "100000",
            "total": 0,
            "confirm_code": 1234,
            "status": 0,
            "created_at": "2020-03-18 22:10:40",
            "updated_at": "2020-03-18 22:10:40"
        },
        {
            "id": 5,
            "invoice_id": 100000,
            "user_id": 1000,
            "contact_number": "NA",
            "province": 0,
            "location": "100000",
            "total": 0,
            "confirm_code": 1234,
            "status": 0,
            "created_at": "2020-03-18 22:12:29",
            "updated_at": "2020-03-18 22:12:29"
        }
    ],
    "message": null
}

我的结构是,

struct Invoice: Codable {
    let statusCode: Int
    let data: [Datum]
    let message: String?

    enum CodingKeys: String, CodingKey {
        case statusCode
        case data, message
    }
}

struct Datum: Codable {
    let id, invoiceID, userID: Int
    let contactNumber: String
    let province: Int
    let location: String
    let total, confirmCode, status: Int
    let createdAt, updatedAt: String

    enum CodingKeys: String, CodingKey {
        case id
        case invoiceID
        case userID
        case contactNumber
        case province, location, total
        case confirmCode
        case status
        case createdAt
        case updatedAt
    }
}

在视图控制器中,

override func viewDidLoad() {
        super.viewDidLoad()

        let url = URL(string: "http://xxxxx/api/invoices/\(1000)")!
        var request = URLRequest(url: url)
        request.httpMethod = "get"
        let task = session.dataTask(with: request) { (data, response, error) in
            guard let data = data else { return }
            do {
                let jsonData = try JSONDecoder().decode([Invoice].self, from: data)
                print(jsonData)
            }
            catch let jsonerr {
                print("error serrializing error",jsonerr)
            }

        }
        task.resume()
    }

但我一直保持以下错误消息,

error serrializing error typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath: [], debugDescription: "期望解码 Array 但找到了一个字典。", underlyingError: nil))

请问我在这里缺少什么!任何帮助将不胜感激

【问题讨论】:

  • 你能解释一下为什么写[Invoice].self而不是Invoice.self吗?
  • 正如 Sweeper 所建议的,在 json 中你只有一个对象而不是对象数组。
  • 除非您指定convertFromSnakeCase策略并删除所有CodingKeys,否则您将收到更多错误。
  • 谢谢大家,括号是我的错误

标签: ios json swift decodable


【解决方案1】:

Codable 结构类似于

struct Invoice: Codable {
    let statusCode: Int
    let data: [Datum]
    let message: String?

    enum CodingKeys: String, CodingKey {
        case statusCode = "status_code"
        case data, message
    }
}

struct Datum: Codable {
    let id, invoiceID, userID: Int
    let contactNumber: String
    let province: Int
    let location: String
    let total, confirmCode, status: Int
    let createdAt, updatedAt: String

    enum CodingKeys: String, CodingKey {
        case id = "id"
        case invoiceID = "invoice_id"
        case userID = "user_id"
        case contactNumber = "contact_number"
        case province, location, total
        case confirmCode = "confirm_code"
        case status
        case createdAt = "created_at"
        case updatedAt = "updated_at"
    }
}

也可以使用

let jsonData = try JSONDecoder().decode(Invoice.self, from: data)

而不是

 let jsonData = try JSONDecoder().decode([Invoice].self, from: data)

【讨论】:

  • 谢谢,我忘了括号(:
猜你喜欢
  • 1970-01-01
  • 2019-02-16
  • 1970-01-01
  • 1970-01-01
  • 2021-09-17
  • 2020-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多