如何在Swift

时间:2018-10-22 16:45:12

标签: ios json swift parsing

要解析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)
}

1 个答案:

答案 0 :(得分:2)

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"
    }

}