如何在Swift中解析特定的JSON?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (46)

要解析JSON,我在网上也发现,我通常使用这种代码:

guard let results = receivedUserJSON["results"] as? [String: Any] else {
    print("Error interpreting results")
    return
}

这次我有一个问题,因为它似乎以这个后卫的其他方式结束了。JSON具有以下结构:

{
    "results": [{
        "gender": "female",
        "name": {
            "title": "mrs",
            "first": "silene",
            "last": "almeida"
        },
        "location": {
            "street": "2594 rua maranhão ",
            "city": "pouso alegre",
            "state": "distrito federal",
            "postcode": 20447,
            "coordinates": {
                "latitude": "-70.0198",
                "longitude": "123.6577"
            },
            "timezone": {
                "offset": "+4:30",
                "description": "Kabul"
            }
        },
        "email": "silene.almeida@example.com",
        "login": {
            "uuid": "d06a46b3-1c00-42be-b8fc-d271bf901f7d",
            "username": "silversnake251",
            "password": "ventura",
            "salt": "UcckU6RG",
            "md5": "7c8c4129587c61da01ca7cf4f88353c5",
            "sha1": "6cbf7ec377ff4ebad5a392ec487343bf613858ef",
            "sha256": "8dedf3649fb833a1936b8885627b86c6cf02062eb74f727b2cbd674a30f73e75"
        },
        "dob": {
            "date": "1969-07-13T00:58:26Z",
            "age": 49
        },
        "registered": {
            "date": "2003-09-28T09:44:56Z",
            "age": 15
        },
        "phone": "(95) 0094-8716",
        "cell": "(20) 1014-3529",
        "id": {
            "name": "",
            "value": null
        },
        "picture": {
            "large": "https://randomuser.me/api/portraits/women/66.jpg",
            "medium": "https://randomuser.me/api/portraits/med/women/66.jpg",
            "thumbnail": "https://randomuser.me/api/portraits/thumb/women/66.jpg"
        },
        "nat": "BR"
    }],
    "info": {
        "seed": "dd971cddf636d2d7",
        "results": 1,
        "page": 1,
        "version": "1.2"
    }
}

我该怎么做才能正确解析这个JSON?我不想选择Codable解决方案,因为我不需要所有这些值。

PS:我知道json是正确的,因为我试过并打印出来:

if let JSONString = String(data: responseData, encoding: String.Encoding.utf8) {
    print(JSONString)
}
提问于
用户回答回答于

results 是一个数组

guard let results = receivedUserJSON["results"] as? [[String:Any]] else {
            print("Error interpreting results")
            return
        }

我认为它不是一个数组的值,因为它包含1个元素,所以你可以考虑改变这个json

目前的结构

{
    "results": [{}],
    "info": {
        "seed": "dd971cddf636d2d7",
        "results": 1,
        "page": 1,
        "version": "1.2"
    }
}

你可以改成它

{
    "results": {},
    "info": {
        "seed": "dd971cddf636d2d7",
        "results": 1,
        "page": 1,
        "version": "1.2"
    }

}

扫码关注云+社区

领取腾讯云代金券