如何在Swift中解析此JSON响应

时间:2019-05-14 13:22:00

标签: ios json swift api response

大家!因此,我通常使用此代码来解析大多数JSON响应

在代码之前,这里需要从JSON中获取“工作区”

{
    "count": 1,
    "next": null,
    "previous": null,
    "results": [{
        "id": 307,
        "email": "999@ios.net",
        "firstName": "fighter",
        "categories": [],
        "workspace": 302,
        "phone": "25485"
    }]
}

这是我的代码:

func getWorkSpace() {
    DispatchQueue.main.async {
        let returnAccessToken: String? = UserDefaults.standard.object(forKey: "accessToken") as? String
        print("UserDefaults Returned Access Token is: \(returnAccessToken!)")
        let access  = returnAccessToken!
        let headers  = [
            "content-type": "application/x-www-form-urlencoded",
            "cache-control": "no-cache",
            "postman-token": "dded3e97-77a5-5632-93b7-dec77d26ba99",
            "Authorization": "JWT \(access)"
        ]
        let request  = NSMutableURLRequest(url: NSURL(string: "https://v5/workspaces/")! as URL,
                                           cachePolicy: .useProtocolCachePolicy,
                                           timeoutInterval: 10.0)

        request.httpMethod          = "GET"
        request.allHTTPHeaderFields = headers

        let session  = URLSession.shared
        let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
            if (error != nil) {
                print(error!)
            } else {
                if let dataNew = data, let responseString = String(data: dataNew, encoding: .utf8) {
                    print("--------")
                    print(responseString)
                    print("--------")

                    DispatchQueue.main.async {
                        do {
                            let json = try JSON(data: data!, options: .allowFragments)
                            let answer = json["results"]
                            let workspace = Int(answer["workspace"].int!)
                        // let workspace = Int(answer["workspace"].string!)!
                        // let workspace  = answer["workspace"].int!
                            print("Workspace is: \(workspace)")
                        } catch {
                            print("Error saving workspace!")
                        }
                    }
                }
            }
        })
        dataTask.resume()
    }
}

此代码通常对我有用,但是这次不行。请不要建议我使用Codables,因为我尚未学习它们。如果有人可以指出我的错误并纠正它,将不胜感激。

2 个答案:

答案 0 :(得分:0)

SwiftyJSON

do {
    let json = try JSON(data: data1!)
    let answer = json["results"].array
    answer?.forEach {
        print($0["workspace"].int!) 
    }

} catch {
    print("Error saving workspace!")
}

JSONSerialization

let json = try! JSONSerialization.jsonObject(with:data, options :[]) as! [String:Any] 
let results = json["results"] as! [[String:Any]]
results.forEach { 
     print($0["workspace"] as! Int)
}

Codable

struct Root : Codable {
   let results:[Model]
}
struct Model: Codable {
    let id: Int
    let email, firstName: String
    let workspace: Int
    let phone: String
}

let res = try! JSONDecoder().decode(Root.self, from:data)
print(res.results)

答案 1 :(得分:0)

只需在您的do块中完成

do {
let json = try JSON(data: data!, options: .allowFragments)
if let answer = json["results"] as? [[String:Any]] {
    for Workspace in answer {
    let workspace = Workspace["workspace"] as? String ?? "" // or Int
    print("Workspace is: \(workspace)")
    }
}

}