Swift 4正确地将JSON字符串解析为对象

时间:2018-01-26 22:40:13

标签: ios json swift

我正在尝试将来自URLSession请求的JSON字符串解析为Swift对象。

我设法获得了第一级属性的数据,但是对于嵌套属性,发生了一些奇怪的事情。而不是:我得到= AND字符串缺少双引号

如何访问date内的published属性,因为我无法执行此操作:print(todo["published"]["date"])

以下是我得到的数据:

[
    "pretty_artists": kida, 
    "published": {
        date = "2015-12-05";
        now = 1517005961;
        time = "18.59";
        timestamp = 1449341947;
    }, 
    "views": 36, 
    "yt_id": cyXbV7EUl14, 
    "play_start": 0, 
    "title": ski ide, 
    "duration": 235, 
    "video_name": skiide,
    "artists": kida
    ]

这是我的功能:

func makeGetCall(todoEndpoint: String) {
        // Set up the URL request
        guard let url = URL(string: todoEndpoint) else {
            print("Error: cannot create URL")
            return
        }
        let urlRequest = URLRequest(url: url)

        // set up the session
        let config = URLSessionConfiguration.default
        let session = URLSession(configuration: config)

        // make the request
        let task = session.dataTask(with: urlRequest) {
            (data, response, error) in
            // check for any errors
            guard error == nil else {
                print("error calling GET on /todos/1")
                print(error!)
                return
            }
            // make sure we got data
            guard let responseData = data else {
                print("Error: did not receive data")
                return
            }
            // parse the result as JSON, since that's what the API provides
            do {
                guard let todo = try JSONSerialization.jsonObject(with: responseData, options: [])
                    as? [String: Any] else {
                        print("error trying to convert data to JSON")
                        return
                }
                // now we have the todo
                // let's just print it to prove we can access it

                print(todo["published"]["date"])


                // the todo object is a dictionary
                // so we just access the title using the "title" key
                // so check for a title and print it if we have one
                guard let todoTitle = todo["title"] as? String else {
                    print("Could not get todo title from JSON")
                    return
                }
                print("The title is: " + todoTitle)
            } catch  {
                print("error trying to convert data to JSON")
                return
            }
        }
        task.resume()
    }

1 个答案:

答案 0 :(得分:0)

尝试使用SwiftyJSON库,它可以帮助您更轻松地解析数据。

https://github.com/SwiftyJSON/SwiftyJSON