簡體   English   中英

在Swift 3中解析嵌套的Json數據

[英]Parsing nested Json data in swift 3

當我從我的api解析json數據時,我得到了意外的值,我在這里可能做錯了,因為我是新手,但是我在收到一個“鍵”之前就獲得了正確的值,但是現在我添加了兩個我似乎無法正確解析值。

這是從我的代碼接收到的地址中收集的json(很抱歉,如果它很難閱讀但仍未解決如何在我的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)

這是從此print(json)獲取的輸出im

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

我知道我不應該在評論部分得到更多信息,但是在收視率部分應該有一些數據?

因此,在接收到json並進行解析后,我需要訪問它的這一部分[“ ratings”] [“ elements”],在那之后,我一切都很好

在此先感謝,並請在我的裸露我是新的迅速

謝謝

試試下面的代碼。 以下代碼中使用的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()
    }

輸出

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM