当我在 swift 中将 Json 字符串转换为字典时,我遇到了问题:Error Domain=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] ?? [:]
}
Json字符串为:[{\"propertyId\":\"1\",\"inspectionTemplateId\":1118,\"value\":[{\"widgetControllerId\":141,\"value\":\"Flood Summary Name\"},{\"widgetControllerId\":142,\"value\":\"属性是否被淹?\"},{\"widgetControllerId\":143,\"值\":\"没有\"}]}]"
方法的用法是:
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)
}
最佳答案
读错君。错误是“允许未设置片段”。 只需设置 .allowFragments 即可。 而已。 (确保响应没有格式错误)
JSONSerialization.jsonObject(with: data!, options: .allowFragments)
关于json - iOS swift :"JSON text did not start with array or object and option to allow fragments not set.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48495999/