我希望在Swift(2.0)中反序列化JSON时不传递任何选项。我最初尝试过:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.14.0/jquery.validate.min.js" type="text/javascript"></script>
但那不能编译,我收到错误:
类型NSJSONReadingOptions不符合协议NilLiteralConvertible
枚举NSJSONReadingOptions没有任何“无”选项,那么如果我不想要这些选项,我该怎么办?
答案 0 :(得分:20)
在swift 2中,你应该使用空数组[]
来表示no options
:
NSJSONSerialization.JSONObjectWithData(data, options: [])
答案 1 :(得分:8)
tldr; Swift 3:跳过选项参数,一切都会好的。
JSONSerialization.jsonObject(with: data)
说明:
在swift 3中,函数调用是
class func jsonObject(with data: Data, options opt: JSONSerialization.ReadingOptions = []) throws -> AnyObject
ReadingOptions是一个选项集,Option Set协议的标题有
/// When you need to create an instance of an option set, assign one of the
/// type's static members to your variable or constant. Alternately, to create
/// an option set instance with multiple members, assign an array literal with
/// multiple static members of the option set. To create an empty instance,
/// assign an empty array literal to your variable.
///
/// let singleOption: ShippingOptions = .priority
/// let multipleOptions: ShippingOptions = [.nextDay, .secondDay, .priority]
/// let noOptions: ShippingOptions = []
表示您可以致电
JSONSerialization.jsonObject(with: data, options: [])
但是,选项已经在函数定义中定义了默认[],因此您可以完全跳过它并调用
JSONSerialization.jsonObject(with: data)
答案 2 :(得分:1)
您还可以为NSJSONReadingOptions
对象使用空构造函数。
NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions())