Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS Swift:"JSON text did not start with array or object and option to allow fragments not set."

Tags:

json

swift

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)
        }
like image 229
B.Saravana Kumar Avatar asked Jan 29 '18 07:01

B.Saravana Kumar


2 Answers

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)
like image 124
Aaban Tariq Murtaza Avatar answered Sep 28 '22 05:09

Aaban Tariq Murtaza


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"

like image 23
jcpennypincher Avatar answered Sep 28 '22 06:09

jcpennypincher