11

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..

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] ?? [:]
}

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\"}]}]"

And the Usage of method was:

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)
        }
rmaddy
  • 314,917
  • 42
  • 532
  • 579
B.Saravana Kumar
  • 1,208
  • 6
  • 20
  • 48

3 Answers3

23

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)
Pang
  • 9,564
  • 146
  • 81
  • 122
Aaban Tariq Murtaza
  • 1,155
  • 14
  • 16
3

You can try this:

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)
Pang
  • 9,564
  • 146
  • 81
  • 122
Kamani Jasmin
  • 691
  • 8
  • 11
0

This type of issue can also occur if you have a misconfigured server or your server is unreachable. If you receive this type of error from JSON deserialization you may try converting the data to a string and print it out. It may reveal an error like "502 Bad Gateway"

jcpennypincher
  • 3,970
  • 5
  • 31
  • 44