ios 在 Swift (2.0) 中正确处理 NSJSONSerialization (try catch)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31296545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Correct handling of NSJSONSerialization (try catch) in Swift (2.0)?
提问by Mirko Brunner
arowmy init works fine in Swift < 2 but in Swift 2 I get a error message from Xcode Call can throw, but it is not marked with 'try' and the error is not handled
at let anyObj = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! [String:AnyObject]
. I think in my case I can′t use a try catch block because super is not initialized at this time. "Try" need a function that throws.
arowmy初始化工作正常斯威夫特<2,但是在斯威夫特2我在Xcode得到一个错误信息Call can throw, but it is not marked with 'try' and the error is not handled
的let anyObj = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! [String:AnyObject]
。我认为就我而言,我不能使用 try catch 块,因为此时 super 未初始化。“尝试”需要一个抛出的函数。
here is my function:
这是我的功能:
required init(coder aDecoder : NSCoder)
{
self.name = String(stringInterpolationSegment: aDecoder.decodeObjectForKey("name") as! String!)
self.number = Int(aDecoder.decodeIntegerForKey("number"))
self.img = String(stringInterpolationSegment: aDecoder.decodeObjectForKey("image") as! String!)
self.fieldproperties = []
var tmpArray = [String]()
tmpArray = aDecoder.decodeObjectForKey("properties") as! [String]
let c : Int = tmpArray.count
for var i = 0; i < c; i++
{
let data : NSData = tmpArray[i].dataUsingEncoding(NSUTF8StringEncoding)!
// Xcode(7) give me error: 'CAll can thorw, but it is not marked with 'try' and the error is not handled'
let anyObj = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! [String:AnyObject]
let label = anyObj["label"] as AnyObject! as! String
let value = anyObj["value"] as AnyObject! as! Int
let uprate = anyObj["uprate"] as AnyObject! as! Int
let sufix = anyObj["sufix"] as AnyObject! as! String
let props = Fieldpropertie(label: label, value: value, uprate: uprate, sufix: sufix)
self.fieldproperties.append(props)
}
}
Xcode mean that:
let anyObj = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! [String:AnyObject]
Xcode 的意思是:
let anyObj = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! [String:AnyObject]
but I have no idea to do here the right think according to this document https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html
但我不知道根据本文档https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html在这里做正确的思考
回答by Rob
The jsonObject
can throw
errors, so put it within do
block, use try
, and catch
any errors thrown. In Swift 3:
该jsonObject
罐throw
的错误,所以把它内do
块,使用try
和catch
出现的任何错误。在 Swift 3 中:
do {
let anyObj = try JSONSerialization.jsonObject(with: data) as! [String: Any]
let label = anyObj["label"] as! String
let value = anyObj["value"] as! Int
let uprate = anyObj["uprate"] as! Int
let sufix = anyObj["sufix"] as! String
let props = Fieldpropertie(label: label, value: value, uprate: uprate, sufix: sufix)
// etc.
} catch {
print("json error: \(error.localizedDescription)")
}
Or, in Swift 4, you can simplify your code by making your struct
conform to Codable
:
或者,在 Swift 4 中,您可以通过使您struct
符合以下条件来简化您的代码Codable
:
struct Fieldpropertie: Codable {
let label: String
let value: Int
let uprate: Int
let suffix: String
}
Then
然后
do {
let props = try JSONDecoder().decode(Fieldpropertie.self, from: data)
// use props here; no manual parsing the properties is needed
} catch {
print("json error: \(error.localizedDescription)")
}
For Swift 2, see previous revision of this answer.
对于 Swift 2,请参阅此答案的先前修订版。
回答by Gerd Castan
JSONSerialization.JSONObject throws ErrorType and not NSError.
JSONSerialization.JSONObject 抛出 ErrorType 而不是 NSError。
so the correct catch is
所以正确的捕获是
do {
let anyObj = try JSONSerialization.JSONObject(with: data, options: []) as! [String:AnyObject]
// use anyObj here
} catch let error {
print("json error: \(error)")
}
The type of error
in catch let error
is ErrorType
error
in的类型catch let error
是ErrorType
回答by trevorj
Don't know if it'll solve your problem, but isn't the method JSONObjectWithData:options:error:
? I think you're missing the error
parameter.
不知道它是否会解决您的问题,但不是方法JSONObjectWithData:options:error:
吗?我认为您缺少error
参数。