【问题标题】:JSON serialization/deserialization Alamofire, SwiftJSON 序列化/反序列化 Alamofire, Swift
【发布时间】:2020-10-19 09:18:59
【问题描述】:

我有这样的 Alamofire 请求:

Alamofire.request("myurl", method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil).responseData { (responseData) in

let data = responseData.data
            
do {
   let country = try JSONDecoder().decode(MYOBJECT.self, from: data)
} catch {
   print(error)
   }
}

MYOBJECTS 来自后端,它看起来像这样:

data class CountryObject(
   val country: String,
   val name: String,
) : ResponseObject

问题是(显然)MYOBJECT 不符合可解码对象。这是错误 => Instance method 'decode(_:from:)' requires that 'MYOBJECT' conform to 'Decodable'

我的问题是我必须复制对象吗?如何使这个对象符合可解码协议?我还需要从 Alamofire 反序列化这个对象(JSON),我的方法正确吗?有什么建议吗?谢谢!

【问题讨论】:

    标签: ios swift api alamofire decodable


    【解决方案1】:

    首先,您的CountryObject 似乎是 Kotlin 而不是 Swift?

    在 Swift 中,让类或结构符合 Decodable 就像这样简单:

    struct CountryObject : Decodable {
        val country : String
        val name : String
    }
    

    【讨论】:

    • 是的,我的 CountyObject 在 Kotlin 中!所以在你的回答中我应该快速复制我的对象?
    • 是的,您需要一个 Swift 版本的 CountryObject 或 MYOBJECT,如果那是您的类/结构的名称。
    • 有什么方法可以使用我的 Kotlin 类并使其可解码?
    【解决方案2】:

    创建一个与后端模型对应的 Swift 模型。看JSON,做出这样的模型:

    struct Country: Decodable {
        var country: String
        var name: String
    }
    

    并使用上述模型对其进行解码,就像它返回单个对象一样:

    let country = try JSONDecoder().decode(Country.self, from: data)
    

    如果是数组:

    let country = try JSONDecoder().decode([Country].self, from: data)
    

    注意:使用quicktype 快速为您的JSON 生成模型:)。

    【讨论】:

    • 有什么方法可以使用我的 Kotlin 类并使其可解码?
    • 不,你不能。您收到的数据为 JSON,其中不包含任何特定语言类的信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-17
    相关资源
    最近更新 更多