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

时间:2018-11-05 23:13:50

标签: swift post alamofire codable

我有一个使用alamofire5 beta的自定义APIClient,该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:复杂,选项:[])

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您可能需要

do {

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

   print(error)
}

因为Codable能够利用JSONDecoderJSONEncoder而不与JSONSerialization一起使用,而String/Array/Dictionary期望像原始String*这样的非定制对象