iOS Swift:"JSON文本不是以数组或对象开头,并且不允许片段设置的选项." [英] iOS Swift:"JSON text did not start with array or object and option to allow fragments not set."
问题描述
当我迅速将Json字符串转换成字典时,出现了问题:错误域= NSCocoaErrorDomain代码= 3840"JSON文本不是以数组或对象开头,并且选项允许不设置片段. UserInfo = {NSDebugDescription = JSON文本不是以数组或对象开头,并且没有允许设置片段的选项.}
When I converting Json string to dictionary in swift I got the Issue:Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
我不知道要解决此问题,请给出解决该问题的想法.在这里,我向我提供了我尝试过的代码.
I don't know to fix the issue please give idea for fix the issue.Here I gave my code what i am tried..
将Json字符串转换为字典的方法是
The method for converting Json string to dictionary is,
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\":\"Did the property flood?\"},{\"widgetControllerId\":143,\"value\":\"no\"}]}]"
The Json String is: "[{\"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)
}
推荐答案
阅读错误信息.错误是不允许设置片段". 只需设置.allowFragments. 而已. (确保响应没有格式错误)
Read the error gentleman. Error is 'allow fragments not set'. Just Just just set .allowFragments. That's it. (Make sure response is not malformatted)
JSONSerialization.jsonObject(with: data!, options: .allowFragments)
这篇关于iOS Swift:"JSON文本不是以数组或对象开头,并且不允许片段设置的选项."的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!