gpt4 book ai didi

swift - 可解码 JSONSerialization 错误自定义对象 alamofire

转载 作者:行者123 更新时间:2023-11-30 11:02:31 25 4
gpt4 key购买 nike

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

Invalid type in JSON write (_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 = try JSONSerialization.data(withJSONObject: complex, options: [])

有什么想法吗?

最佳答案

您可能需要

do {

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

print(error)
}

as Codable 用于能够利用 JSONDecoderJSONEncoder,而不是与期望的 JSONSerialization 一起使用非自定义对象,例如原始 String/Array/Dictionary

关于swift - 可解码 JSONSerialization 错误自定义对象 alamofire,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53163666/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com