Swift 4 Decodable, DecodingError : No value associated with key

Swift 4 Decodable, DecodingError : No value associated with key

我正在尝试使用 Swift 4 Codable 功能,但遇到了这种情况:

struct Message:Codable {

let message: String
let timestamp: String
let latitude: String
let longitude: String}

这是我的结构。

guard let url = URL(string:"http://localhost:443/api/message") else {return}
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    print("POSTED")

    let newPost = Message(message: "Hi", timestamp: "1", latitude: "1.1", longitude: "2.2")

    print("NewPost:",newPost)

    do {
        let jsonBody = try JSONEncoder().encode(newPost)
        request.httpBody = jsonBody

    } catch let err  {
        print("jsonBody Error: ",err)
    }

    let session = URLSession.shared
    let task = session.dataTask(with: request){ (data,response,err) in
        guard let data = data else {return}
        do{
            let sendPost = try JSONDecoder().decode(Message.self, from: data)
            print("sendPost:\(sendPost)")
        }catch let err{
            print("Session Error: ",err)
        }
    }
    task.resume()
}

这是我用于 post 请求的函数。 在 print("NewPost:",newPost) 中,它打印

NewPost: Message(message: "Hi", timestamp: "1", latitude: "1.1", longitude: "2.2")

这看起来与我看到的其他示例非常相似, 但是 catch

总会出现会话错误
Session Error:  keyNotFound(DeadDrop.Message.(CodingKeys in _5C64F74710315F52702B56CE54E28C19).message, Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key message (\"message\").", underlyingError: nil))

我只是不明白这是怎么来的!我正在使用完全相同的结构,它说没有密钥?! 感谢您的帮助!

SQLState: 22007 : The string representation of a datetime is not in the acceptable range or is not in the correct format.

正如您所说,您得到的 data 如下:

{"code":"ER_TRUNCATED_WRONG_VALUE","errno":1292,"sqlSta‌​te":"#22007"}

根据此 link,它期望与您发送的数据类型不同。

我怀疑您发送的 timestamp1,这不是有效的 timestamp

尝试将 timestamp 值发送为“1508309342”

除此之外你的解码代码没问题。