10
votes

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)
        }
3
Your JSON is invalid. Try running your test through a JSON validator first. - john elemans
is this valid json - Anbu.Karthik
try using try JSONSerialization.jsonObject(with: data, options: [.allowFragments]) - Reinier Melian
Your JSON is an Array at top level by the way, an array of dictionary, but once you removed "\" before the ", it seems valid so you shouldn't get that error, you should get another one: returning empty: [:]. - Larme
Why do you convert Data to (NS)String and then back to Data? Print the data (print(data as NSData)) and post the first bytes. And don't use NSString and NSDictionary in Swift. - vadian

3 Answers

18
votes

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)
3
votes

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)
1
votes

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"