简体   繁体   English

如何在 Swift 中解析以下 JSON?

[英]How to parse the following JSON in Swift?

{"response":{"success":true,"access_token":"z5zbXVfaD4xOyTCLOwLIBPvuEYw7lQCUWb5U7l4KpCyXvbJkHv2jkyOZwk6RbJM7VS12d5NDImBeykygPBAa9o9FJgxUZk1Uc2Xp","access_level":"1"}}

How do I parse the response individually?如何单独解析响应? I would like to get every object in separate variable.我想将每个对象都放在单独的变量中。 My code:我的代码:

var reponseError: NSError?
        var response: NSURLResponse?
        var urlData: NSData?


        do {
            urlData = try? NSURLConnection.sendSynchronousRequest(request, returningResponse:&response)
        }
        catch(let e) {
            print(e)
        }

        if ( urlData != nil ) {
            let res = response as! NSHTTPURLResponse!;

            NSLog("Response code: %ld", res.statusCode);

            if (res.statusCode >= 200 && res.statusCode < 300)
            {
                var responseData:NSString  = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!

                NSLog("Response ==> %@", responseData);

For simple JSON parsing you can use NSJSONSerialization对于简单的 JSON 解析,您可以使用NSJSONSerialization

var decodedJson : AnyObject
do {
    decodedJson = try NSJSONSerialization.JSONObjectWithData(urlData!, options: .MutableContainers)
}
catch (let e) {
    //Error in parsing
    print(e)
}

This will return a Dictionary with all key / value pairs of the response JSON.这将返回一个包含响应 JSON 的所有键/值对的字典。 You can simply use this dictionary to get value of required keys.您可以简单地使用此字典来获取所需键的值。

But, a better approach would be to create a model class for response.但是,更好的方法是为响应创建一个模型类。

In your case it may be something like:在您的情况下,它可能类似于:

class ResponseModel {

    var success : Bool?
    var accessToken : String?
    var accessLevel : Int?

    init(dictionary : NSDictionary) {

        if let successValue = dictionary["success"] as? Bool {
            success = successValue
        }
        if let accessTokenValue = dictionary["access_token"] as? String{
            accessToken = accessTokenValue
        }
        if let accessTokenValue = dictionary["access_level"] as? Int{
            accessLevel = accessTokenValue
        }
    }
}

Then you can update your code to create a ResponseModel object:然后你可以更新你的代码来创建一个ResponseModel对象:

if (res.statusCode >= 200 && res.statusCode < 300)
{
    var responseData:NSString  = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!

    NSLog("Response ==> %@", responseData);

    //JSON serialization
    var decodedJsonResponse : NSDictionary?
    do {

        decodedJsonResponse = try NSJSONSerialization.JSONObjectWithData(urlData!, options: .MutableContainers) as? NSDictionary
    }
    catch (let e) {
        //Error in parsing
        print(e)
    }

    //Use JSON response dictionary to initialize the model object
    if let decodedJson = decodedJsonResponse?["response"] as? NSDictionary {
        let responseObject = ResponseModel(dictionary: decodedJson)

        //use responseObject as required
        print(responseObject)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM