简体   繁体   中英

Unable to get the value of JSON - Swift

I tried to get the value of "seed" from json response. But i am getting nil.

Json Response:

{
        "response": {
            "params": {
                "rows": "20",
                "defType": "abc",
                "seed": "381786611"
            }
        }
    }

Swift Parsing:

if let responseHeader:AnyObject = object?["response"] as? NSDictionary {
    if let t = (responseHeader["params"] as? NSDictionary){
       let t1 = t["seed"] as? String
       println("result is \(t1)") // This returns nil
     }
}

Json Parsing

 func processJsonToDictionary(object:AnyObject?) -> AnyObject?{
        if object != nil {
            if let data: AnyObject = object {
                var parseError: NSError?

                var jsonResult = NSJSONSerialization.JSONObjectWithData(object as NSData!, options: NSJSONReadingOptions.MutableContainers, error: &parseError) as? NSDictionary
                if(parseError != nil){
                    return parseError
                }
                else{
                    return jsonResult
                }
            }
        }
        return nil
    }

I am not able to get the value of t1. it always returns nil. How can i get the value.

Also, I put a breakpoint and tried to print the value of t1. But the Xcode Keeps crashing. Why?

I think the major problem here is only accessing a JSON object in swift.

var error: NSError?
let jsonDict = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) as NSDictionary
let resp = jsonDict["response"] as? NSDictionary
let params = resp?["params"]?["seed"]
let seed = params!! as NSString

This is just to show you how a JSON object is accessed in swift. You can ofcourse change it according to your needs to remove unwanted Optional Chaining.

For easy JSON manipulation in Swift you could try this little library. It seems pretty easy and you could do this:

var dictionary: [String: AnyObject]!
if let json = NKJSON.parse(yourNSDataObject) {
    dictionary <> json[NKJSON.rootKey]
}

First confirm that the response which you are getting is in json format or in string format. For json parsing you can use swifty json pod

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