在swift 3中解析嵌套的Json数据

时间:2017-09-09 17:22:44

标签: json swift api parsing swift3

当我从我的api解析我的json数据时,我得到了意想不到的值,我可能在这里做错了,因为我对swift很新,但是当我收到一个&之前我得到了正确的值#34;键"但现在我已经添加了两个,我似乎无法正确解析这些值。

这是从我的代码收到的地址中收集的json,(对不起,如果它很难读懂havn&n来解决如何在我的ruby api中进行换行)(只要它的功能我不太此刻担心)

           {
    "ratings":{
    "elements":{"Ready Position":[{"description":"Neutral Grip","values":"1,2,3,4,5"},{"description":"Back Straight (Concave ir Convex?)","values":"1,2,3,4,5"},{"description":"Body Low \u0026 Feet a little more than sholder width apart","values":"1,2,3,4,5"},{"description":"Weight on Balls of Feet","values":"1,2,3,4,5"},{"description":"Head Up","values":"1,2,3,4,5"},{"description":"Sholder Blades Close","values":"1,2,3,4,5"},{"description":"Eyes Drilled","values":"1,2,3,4,5"}],"Split Step":[{"description":"Ready Position Conforms","values":"Yes,No"},{"description":"Body Position Low","values":"1,2,3,4,5"},{"description":"Legs Loaded/Prepared","values":"1,2,3,4,5"}]}
},
    "comments":{}
}

现在,我的快速代码看起来像这样

 let playerAPIurl = "http://linkcoachuat.herokuapp.com/api/v1/session/element?organisation=" + userorganisation + "&group=" + urlGroupSelected + "&sport=" + usersport
    print(playerAPIurl)
    var request = URLRequest(url: URL(string: playerAPIurl)!)
    request.httpMethod = "GET"



    let configuration = URLSessionConfiguration.default
    let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)

    let task = session.dataTask(with: request) { (data, response, error) in
        if error != nil {
            print("ERROR")
        }
        else{

            do {


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

                print(json)

这是我从这个印刷品(json)获得的输出

Optional({
    comments =     {
    };
    ratings =     {
    };
})

我知道我不应该在评论部分获得更多内容,但在评级部分应该有一些数据?

所以在收到json并处理解析之后,我需要访问它的这一部分["评级"] ["元素"]然后我很好

提前感谢,请在我的手机上露出我非常新的快速

由于

1 个答案:

答案 0 :(得分:0)

尝试以下代码。以下代码中使用的url包含您的JSON数据。此代码正确打印输出。

 func testApi(){
        let url = URL(string: "https://api.myjson.com/bins/jfccx")

        let session = URLSession.shared
        let request = URLRequest(url: url!)

        //create dataTask using the session object to send data to the server
        let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in

            guard let data = data, error == nil else {
                return
            }

            do {
                //create json object from data
                if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
                    print(json)
                }

            } catch let error {
                print(error.localizedDescription)
            }
        })
        task.resume()
    }

output