简体   繁体   English

无法获取JSON的值-Swift

[英]Unable to get the value of JSON - Swift

I tried to get the value of "seed" from json response. 我试图从json响应中获取“种子”的值。 But i am getting nil. 但是我越来越没有了。

Json Response: Json回应:

{
        "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. 我无法获得t1的值。 it always returns nil. 它总是返回nil。 How can i get the value. 我如何获得价值。

Also, I put a breakpoint and tried to print the value of t1. 另外,我设置了一个断点并尝试打印t1的值。 But the Xcode Keeps crashing. 但是Xcode一直崩溃。 Why? 为什么?

I think the major problem here is only accessing a JSON object in swift. 我认为这里的主要问题只是快速访问JSON对象。

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. 这只是向您展示如何快速访问JSON对象。 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. 为了在Swift中轻松进行JSON操作,您可以尝试使用这个小库。 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. 首先确认您得到的响应是json格式还是字符串格式。 For json parsing you can use swifty json pod 对于json解析,您可以使用swifty json pod

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

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