【问题标题】:Decodable JSONSerialization error custom object alamofire可解码 JSONSerialization 错误自定义对象 alamofire
【发布时间】:2019-04-09 08:38:24
【问题描述】:

我有一个使用 alamofire5 beta 的自定义 APIClient,它符合 Codable 协议的请求。 我正在尝试通过 httpBody (post) 发送自定义对象,但出现此错误:

JSON 写入中的类型无效 (_SwiftValue)

这是我要发送的对象:

struct Complex: Codable {
    var id: String
    var name: String
    var address: String
    var zipcode: String
    var amenities: [String]
    var schedules: [ComplexSchedules]

    init(id: String, name: String, address: String, zipcode: String, amenities: [String], schedules: [ComplexSchedules]) {
        self.id = id
        self.name = name
        self.address = address
        self.zipcode = zipcode
        self.amenities = amenities
        self.schedules = schedules
    }

    enum CodingKeys: String, CodingKey {
        case id = "id"
        case name = "name"
        case address = "address"
        case zipcode = "zipcode"
        case amenities = "amenities"
        case schedules = "schedules"
    }

    struct TimeRange: Codable {
        var from: String
        var to: String

        init(from: String, to: String) {
            self.from = from
            self.to = to
        }

        enum CodingKeys: String, CodingKey {
            case from = "from"
            case to = "to"
        }
    }

    struct ComplexSchedules: Codable {
        var day: String
        var timeRanges: [TimeRange]

        init(day: String, timeRanges: [TimeRange]) {
            self.day = day
            self.timeRanges = timeRanges
        }

        enum CodingKeys: String, CodingKey {
            case day = "day"
            case timeRanges = "time_ranges"
        }
    }
}

调用此方法失败:

urlRequest.httpBody = 试试 JSONSerialization.data(withJSONObject: complex, options: [])

有什么想法吗?

【问题讨论】:

    标签: swift post alamofire codable


    【解决方案1】:

    你可能需要

    do {
    
         let data = try JSONEncoder().encode(complex)
         urlRequest.httpBody = data
    }
    catch {
    
       print(error)
    }
    

    因为 Codable 用于能够使用 JSONDecoderJSONEncoder 不能与 JSONSerialization 一起使用,因为 JSONSerialization 需要像原始 String/Array/Dictionary 这样的非自定义对象

    【讨论】:

    • 谢谢!像魅力一样工作。
    • @Gerkor 您可以查看 Alamofire 的 feature/encodable-requests 分支以获取正在进行的版本,该版本增加了对带有 Encodable 主体的请求的支持。目前只支持 JSON 编码,但表单编码也应该支持。
    猜你喜欢
    • 1970-01-01
    • 2017-02-22
    • 1970-01-01
    • 2015-09-21
    • 1970-01-01
    • 1970-01-01
    • 2021-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多