2017-10-18 49 views
0

我试图用斯威夫特4可编码的功能,但被困在这种情况下,相关值:斯威夫特4解码的,DecodingError:没有与关键

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() 
} 

这是我用于发布请求的函数。 在打印(“NewPost:” newPost),它打印

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

它看着我看到其他的例子, 很相同的,但再有就是总是被抓

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

我一个会话错误只是不明白这是怎么回事!我使用完全相同的结构,它说这没有关键吗?! 感谢您的帮助!

+0

你可以发布什么是你的'数据'打印? –

+0

它与Message对象的编码方式有关。你可以发布Message类的代码吗? – NSAdi

+0

如果我在打印(“Session Error:”,err)后使用print(“DATA:\(data)”),它会打印出“DATA:68 bytes”...我怎么看到里面有什么? @ViniApp – Kei

回答

0

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”

除此之外,你的解码程序代码是好的。

+0

谢谢!我实际上有时间戳的格式('timestamp:2017-09-10 10:22:33'),但我认为这个错误是由JSON无法解码造成的。所以知道这是从服务器的错误真的帮助! – Kei

+0

哦,等等,很抱歉,但我只是注意到它显示''没有与关键信息(\“message \”)相关联的值。“”为什么它不接受我的信息而不是时间戳?该消息除<280个字符的字符串外没有其他限制。 – Kei