gpt4 book ai didi

arrays - Swift:检查 jsonObjectWithData 是否为 json

转载 作者:搜寻专家 更新时间:2023-11-01 06:22:33 24 4
gpt4 key购买 nike

我有一个通过 http 与服务器通信的 swift 应用程序,

我从这个服务器得到的答案可能是json,也可能不是。我需要检查它们是什么,以便将答案打印为 DictionaryArray,以避免 fatal error: unexpectedly found nil while unwrapping an NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableContainers, error: nil) 中的可选值 as! NSDictionary

这是我的jsonObjectWithData:

var dataVal: NSData =  NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error:nil)!
elimResponse = response?.description
elim = NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary

我试图得到的是这样的:

if dataVal is Json{
elim = NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary
println(elimJson)
}else{
elim = NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSArray
println(elim)
}

感谢您的帮助。问候。

最佳答案

您可以像这样在 if let 中尝试强制转换:

if let elim = NSJSONSerialization.JSONObjectWithData(dataVal, options: nil, error: nil) as? NSDictionary {
println("elim is a dictionary")
println(elim)
} else if let elim = NSJSONSerialization.JSONObjectWithData(dataVal, options: nil, error: nil) as? NSArray {
println("elim is an array")
println(elim)
} else {
println("dataVal is not valid JSON data")
}

Swift 2.0 更新

do {
if let elim = try NSJSONSerialization.JSONObjectWithData(dataVal, options: []) as? NSDictionary {
print("elim is a dictionary")
print(elim)
} else if let elim = try NSJSONSerialization.JSONObjectWithData(dataVal, options: []) as? NSArray {
print("elim is an array")
print(elim)
} else {
print("dataVal is not valid JSON data")
}
} catch let error as NSError {
print(error)
}

关于arrays - Swift:检查 jsonObjectWithData 是否为 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31287958/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com