当我在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
print(dictionary)
} catch {
print(error)
}
Run Code Online (Sandbox Code Playgroud)
Aab*_*aza 11
读错误绅士.错误是'允许片段未设置'.只需设置.allowFragments即可.而已.(确保响应没有格式错误)
JSONSerialization.jsonObject(with: data!, options: .allowFragments)
Run Code Online (Sandbox Code Playgroud)
你可以试试这个:
let str = "[{\"propertyId\":\"1\",\"inspectionTemplateId\":1118,\"value\":[{\"widgetControllerId\":141,\"value\":\"Flood Summary Name\"},{\"widgetControllerId\":142,\"value\":\"Did the property flood?\"},{\"widgetControllerId\":143,\"value\":\"no\"}]}]".utf8
let json = try! JSONSerialization.jsonObject(with: Data(str), options: [])
print(json)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13492 次 |
| 最近记录: |