简体   繁体   English

iOS SWIFT-NSJSONSerialization后的JSON对象为nil

[英]iOS SWIFT - JSON object nil after NSJSONSerialization

hello I am trying to read JSON as an array from the server not the dictionary. 你好,我试图从服务器而不是字典中读取JSON作为数组。 If I do this 如果我这样做

let json: NSArray?
do {
    json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as! NSArray
    print("json is \(json)")
}

json object comes nil through this code and also I can't access the variable like this json["code"] I have tried this too json对象通过此代码变为nil,而且我也无法访问像json["code"]这样的变量,我也尝试过

NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as! NSArray

But If I don't specify any type and let the variable as AnyObject 但是,如果我不指定任何类型并将变量设置为AnyObject

do {
    let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)
    print("json is \(json["code"]!)")                    
} 

It works But 1st problem here is it prints Optional in the debugger but its least of my worries compared to that I can't do something like this 它可以工作,但是这里的第一个问题是它在调试器中打印Optional,但是与我无法做到的事情相比,我的担心最少

if json["code"] == 200 { 

}

If I do this it says 如果我这样做,它会说

Binary operator '==' cannot by applied to operands of type Anyobject? 二进制运算符'=='无法应用于类型AnyObject的操作数吗? and Int 和诠释

what I want is to get the data in NSArray . 我想要的是获取NSArray的数据。 I don't want the json variable to be set as AnyObject . 我不希望将json变量设置为AnyObject Inshort I want this code to work 简而言之,我希望这段代码能正常工作

let json: NSArray?
do {
    json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as! NSArray
    print("json is \(json)")
} 

if its possible. 如果它是可能的。 I don't know what I am doing wrong here 我不知道我在做什么错

json: json:

 {"code":200,"msg":"login success"}

If printing json["code"] works, then json is doubtless a dictionary. 如果打印json["code"]有效,那么json无疑是字典。

JSONObjectWithData returns AnyObject that is "I-have-no-idea-what-it-is-but-it-is-some-kind-of-object-and-not-a-value" (thanks to gnasher729 for the more accurate paraphrase of AnyObject ) JSONObjectWithData返回AnyObject ,它“我没有什么想法,但是它是某种对象并且没有值”(感谢gnasher729的准确性释义AnyObject

Since you know the object is [String:AnyObject] cast the type 因为您知道对象是[String:AnyObject]所以将类型[String:AnyObject]

let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as! [String:AnyObject]

Then get the code – which is an Int – with 然后获取代码-这是一个Int

if json["code"] as! Int == 200 { 

}

or with optional binding if the key is optional 或带有可选绑定(如果密钥是可选的)

if let code = json["code"] as? Int { 
   if code == 200 {

   }
}

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

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