【问题标题】:My Json string is not decoding using JSONSerialization.jsonObject()我的 Json 字符串未使用 JSONSerialization.jsonObject() 解码
【发布时间】:2023-04-05 09:19:01
【问题描述】:

我从我的 HTTP 请求中接收到一个有效的 Json 字符串,如下所示

"[{
    "id”:10,
    "user_id":"77da74e6-3e03-403d-9c1a-91f231233515”,
    "friend_user_id":"fc879bf5-c53d-4a4e-b3a4-dab7a8266a2r”,
    "name":"Tommie Smith”,
    "type":"active”,
    "created_at":"2018-05-02 14:53:09",
    "updated_at":"2018-05-02 14:53:09",
    "friend_user":{
        "id":"fc879bf5-c53d-4a4e-b3a4-dab7a8266a2r",
        "first_name”:”Allen”,
        "last_name”:”Williams”,
        "email”:”allen.williams@example.org",
        "date_of_birth":"1996-03-05 00:00:00",
        "created_at":"2018-05-02 14:53:07",
        "updated_at":"2018-05-02 14:53:07",
        "deleted_at":null
    }
},
{
    "id”:11,
    "user_id":"77da74e6-3e03-403d-9c1a-91f231233515”,
    "friend_user_id":"96990d13-372e-46f7-9187-94988954455b”,
    "name":"Mr. Thomas Atkins”,
    "type":"not",
    "created_at":"2018-05-02 14:53:10",
    "updated_at":"2018-05-02 14:53:10",
    "friend_user":{
        "id":"96990d13-372e-46f7-9187-94988954455b",
        "first_name”:”Trevor”,
        "last_name”:”Wright”,
        "email”:”trevor.wright@example.net",
        "date_of_birth":"1983-07-27 00:00:00",
        "created_at":"2018-05-02 14:53:08",
        "updated_at":"2018-05-02 14:53:08",
        "deleted_at":null
    }
}]"

我知道这是我收到的,因为我正在使用以下代码返回包含我的数据的字符串

let string = String(data: data, encoding: String.Encoding.utf8)

但是,当我使用下面的代码解析我的数据时,json 返回 nil

let json = try JSONSerialization.jsonObject(with: data) as? [String: AnyObject]

这句话有什么问题?

【问题讨论】:

  • 您能否检查一下您问题中的 JSON。有多少 smart quotes 实际上应该在那里,有多少是应用程序翻译它们的结果?

标签: json swift xcode parsing serialization


【解决方案1】:

请(学习)阅读 JSON,这很容易。只有 2(两种!)不同的集合类型:

  • {} 是字典,在 Swift 中为 [String: Any]
  • [] 是数组,在 Swift 中是 [Any],但在大多数情况下是字典数组 [[String: Any]]

所以 JSON 显然是一个数组。在 Swift 3+ 中,JSON 值为 never AnyObject

let json = try JSONSerialization.jsonObject(with: data) as? [[String: Any]]

注意:

错误的双引号不是错误原因,否则jsonObject(withthrow出错

【讨论】:

  • 你的答案总是很棒@vadian
猜你喜欢
  • 2020-06-02
  • 2019-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多