我JSONSerialization经常在我的项目中使用.这是我的JSONSerialization代码示例:
let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: Any]
Run Code Online (Sandbox Code Playgroud)
注意:目的缺少选项,我通常在项目中使用它们.
我的问题是我不确定这些是options: []做什么的?
我发现的选项:
NSJSONReadingMutableContainers:
指定将数组和字典创建为可变对象.
NSJSONReadingMutableLeaves:
指定将JSON对象图中的叶字符串创建为NSMutableString的实例.
NSJSONReadingAllowFragments:
指定解析器应允许不是NSArray或NSDictionary实例的顶级对象.
注2:我在以下网址找到了这些定义:https://developer.apple.com/reference/foundation/nsjsonreadingoptions
我的问题是:有人可以解释我这些选项之间的差异,我应该使用它们,如果你能告诉我这些选项的代码示例,它将是完美的:).
任何帮助赞赏.
谢谢.
当我在swift中将Json字符串转换为字典时,我得到了问题:错误域= NSCocoaErrorDomain Code = 3840"JSON文本没有以数组或对象开头,并且选项允许未设置片段." UserInfo = {NSDebugDescription = JSON文本不以数组或对象开头,并且选项允许未设置片段.}
我不知道要解决这个问题,请给出解决问题的想法.在这里,我给了我的代码我尝试了什么..
将Json字符串转换为字典的方法是,
func convertToDictionary(from text: String) throws -> [String: String] {
guard let data = text.data(using: .utf8) else { return [:] }
let anyResult: Any = try JSONSerialization.jsonObject(with: data, options: [])
return anyResult as? [String: String] ?? [:]
}
Run Code Online (Sandbox Code Playgroud)
Json字符串是: "[{\"propertyId\":\"1\",\"inspectionTemplateId\":1118,\"value\":[{\"widgetControllerId\":141,\"value\":\"Flood Summary Name\"},{\"widgetControllerId\":142,\"value\":\"Did the property flood?\"},{\"widgetControllerId\":143,\"value\":\"no\"}]}]"
方法的用法是:
let jsonString = NSString(data: responseObject as! Data, encoding: String.Encoding.utf8.rawValue)!
print(jsonString)
do {
let dictionary:NSDictionary = try self.convertToDictionary(from: jsonString as String) as NSDictionary …Run Code Online (Sandbox Code Playgroud)