无法将数据投射到字典中

时间:2019-06-20 17:10:09

标签: ios json swift casting

我有一个JSONObject,我想将其转换为它的类。

我尝试使用JSONSerialization.data(withJSONObject:data,options:[] 并将其编码为.utf8字符串,但没有成功。...


 socket.on("privateMessage") {data, ack in

            print("privateMessage :\(data[0])");

            guard let jsonData = try? JSONSerialization.data(withJSONObject: data, options: []) else {return}

结果:

(lldb) po data
▿ 1 element
  - 0 : {"emisor":105,"receptor":54,"receptor_token":"7ec66175309aac4cbeda0c9936991cfdfcad8445fdcff583524d940c7e0ee4669488675c214823e0","texto":"Dshfljkhdlsafh","updated_at":"2019-06-20 16:38:30","created_at":"2019-06-20 16:38:30","id":10056,"time":"16:38:30"}

(lldb) po jsonData
▿ 282 bytes
  - count : 282
  ▿ pointer : 0x00007f917289f000
    - pointerValue : 140262668627968


2 个答案:

答案 0 :(得分:0)

这样,您可以获得任何密钥的数据。我向您展示了获取receptor_token密钥值的示例。

if let response = jsonData as? [Any] {
    if let responseData = response[0] as? [String:Any] {
       if let receptorToken = responseData["texto"] as? String {
             print(receptorToken)
       }

    }

}

答案 1 :(得分:0)

这是一种非常不寻常的响应格式,从注释的输出来看,它是一个未指定的数组([Any]),其中包含一个JSON字符串,例如

let json = """
{"emisor":105,"receptor":54,"receptor_token":"6b6295e0b0601146e56ff4a9caec287f0ecc0f385fcfcd758dccd00c6385c558eefc6d6fbe98e977","texto":"Blanca bla","updated_at":"2019-06-21 10:48:22","created_at":"2019-06-21 10:48:22","id":10074,"time":"10:48:22"}
"""

let data : [Any] = [json]

为方便起见,首先声明一个结构

struct Response: Decodable {
    let emisor, receptor, id: Int
    let receptorToken, texto, updatedAt, createdAt, time: String
}

要解析JSON,请检查data是否为数组,数组中是否有一个字符串,成功后将其转换为Data并使用Decodable进行解码

socket.on("privateMessage") {data, ack in
    if let response = data as? [Any], let jsonString = response.first as? String {
       let jsonData = Data(jsonString.utf8)
       do {
           let decoder = JSONDecoder()
           decoder.keyDecodingStrategy = .convertFromSnakeCase
           let result = try decoder.decode(Response.self, from: jsonData)
           print(result)
       } catch {
           print(error)
       }
   }
}