我正在尝试通过Alamofire提交以下请求,但收到以下错误:
2020-01-13 09:41:05.912103-0600 AFNetworkingDemo[29720:604258] *** 由于未捕获的异常"NSInvalidArgumentException"而终止应用程序,原因:"JSON 写入中的类型无效 (__SwiftValue(">
我的假设是,这是我在对象中定义数组的方式(我遵循了这里找到的一些材料:https://benscheirman.com/2017/06/swift-json(
struct ProgramRequest: Codable {
var userID: Int
var programData: ProgramData
var json: Constants.Json {
return [
"userID": userID,
"programData": programData.json,
]
}
}
struct ProgramData: Codable {
var airhotel: [AirHotel]
var security: [Security]
var json: Constants.Json {
return [
"airhotel": airhotel,
"security": security
]
}
}
struct AirHotel: Codable {
var id: Int
var loyaltyNumber: String
var json: Constants.Json {
return [
"id": id,
"loyaltyNumber": loyaltyNumber
]
}
}
struct Security: Codable {
var vendorCode: String
var loyaltyNumber: String
var json: [String: Any] {
return [
"vendorCode": vendorCode,
"loyaltyNumber": loyaltyNumber
]
}
}
每个级别的 json 字典都是为 Alamofire 适当地渲染对象。对于给定的示例,如果我使用以下方法将其打印出来:
let jsonEncoder = JSONEncoder()
jsonEncoder.outputFormatting = .prettyPrinted
let jsonData = try jsonEncoder.encode(programRequest)
if let jsonString = String(data: jsonData, encoding: .utf8) {
print(jsonString) #1
}
print("IsValidJSON: ", JSONSerialization.isValidJSONObject(programRequest)) #2
print(programRequest.json) #3
urlRequest = try! JSONEncoding.default.encode(urlRequest, with: programRequest.json) #4 causes error
1 个输出:
{
"userID" : 10021,
"programData" : {
"airhotel" : [],
"security" : [
{
"vendorCode" : "sty",
"loyaltyNumber" : "Loyal1"
}
]
}
}
2 路输出 IsValidJSON: false
3 输出 - 我注意到输出中的 AFNetworkingDemo.Security,是 Alamofire JSONEncoding 上的:
["programData": ["security": [AFNetworkingDemo.Security(vendorCode: "sty", loyaltyNumber: "Loyal1")], "airhotel": []], "userID": 10021]
我的问题是,我需要在ProgramRequest的AirHotel和安全部分进行哪些更改才能解决我在Alamofire上的问题?
第 1 步:停止重新发明 Codable
不需要 json 计算属性,并且错误地使用了该属性。
删除它。
struct ProgramRequest: Codable {
var userID: Int
var programData: ProgramData
}
struct ProgramData: Codable {
var airhotel: [AirHotel]
var security: [Security]
}
struct AirHotel: Codable {
var id: Int
var loyaltyNumber: String
}
struct Security: Codable {
var vendorCode: String
var loyaltyNumber: String
}
第 2 步:开始使用可编码
现在给一个programRequest
,例如像这样
let programRequest = ProgramRequest(userID: 1, programData: ProgramData(airhotel: [AirHotel(id: 1, loyaltyNumber: "loyaltyNumber")], security: [Security(vendorCode: "loyaltyNumber", loyaltyNumber: "loyaltyNumber")]))
您可以生成表示 JSON 的正确数据值,只需写入
let data = try JSONEncoder().encode(programRequest)
并且(如果需要(您可以转换数据介绍字符串
let json = String(data: data, encoding: .utf8)
输出
Optional("{"userID":1,"programData":{"airhotel":[{"id":1,"loyaltyNumber":"loyaltyNumber"}],"security":[{"vendorCode":"loyaltyNumber","loyaltyNumber":"loyaltyNumber"}]}}")
就是这样