在JSON文件swift中读取URL HTTPS

时间:2017-12-05 08:15:13

标签: json swift url request

我尝试在json中读取URL请求(在字典“vehicle”中),但数组将为空 这是json,我需要阅读车辆中的字典和网址

{
"count": 87, 
"next": "https://swapi.co/api/people/?page=2", 
"previous": null, 
"results": [
    {
        "name": "Luke Skywalker", 
        "height": "172", 
        "mass": "77", 
        "hair_color": "blond", 
        "skin_color": "fair", 
        "eye_color": "blue", 
        "birth_year": "19BBY", 
        "gender": "male", 
        "homeworld": "https://swapi.co/api/planets/1/", 
        "films": [
            "https://swapi.co/api/films/2/", 
            "https://swapi.co/api/films/6/", 
            "https://swapi.co/api/films/3/", 
            "https://swapi.co/api/films/1/", 
            "https://swapi.co/api/films/7/"
        ], 
        "species": [
            "https://swapi.co/api/species/1/"
        ], 
        "vehicles": [
            "https://swapi.co/api/vehicles/14/", 
            "https://swapi.co/api/vehicles/30/"
        ], 

这是我尝试的代码

if let results = json["results"] as? [[String : AnyObject]] {

                    var finalArray2 : [String] = []
                    for result in results {
                        if let dict = result as? [String: Any], let vehicles = dict["vehicles"] as? String{
                            self.URLveicoli = vehicles
                            //print(self.nomepersonaggio)
                            print(self.URLveicoli)
                            //finalArray.append(name)
                            finalArray2.append(vehicles)

                        }
                    }
                    print(finalArray2)

                }

1 个答案:

答案 0 :(得分:1)

在json this.projectlist中是一个字符串数组(url)而不是字符串。

更改此

vehicles

let vehicles = dict["vehicles"] as? String

并附加一系列的车辆

let vehicles = dict["vehicles"] as? [String]