简体   繁体   中英

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

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. 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:

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)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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