我的Json字符串没有使用JSONSerialization.jsonObject()进行解码

时间:2018-05-10 08:51:42

标签: json swift xcode parsing serialization

我从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]

这句话有什么问题?

1 个答案:

答案 0 :(得分:2)

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

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

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

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

注意:

错误的双引号不是错误原因,否则jsonObject(with throw 错误