1

I got json response from server like this:

"{\"userID\":\"dkjagfhaghdalgalg\"}"

I try to get that userID with this:

let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
                        (data, response, error) -> Void in
                        if let unwrappedData = data {
                            do {
                                let userIDDictionary:NSDictionary = try NSJSONSerialization.JSONObjectWithData(unwrappedData, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
                                print("userIDDictionary:\(userIDDictionary)")
                                //let userID:String = userIDDictionary["userID"] as! String
                                //print("userID:\(userID)")
                                print("data:\(data)")
                                print("response:\(response)")
                                print("error:\(error)")
                            } catch {
                                print("Failed to get userID: \(error)")
                            }
                        }
                    }

but the response is

Failed to get userID: 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.}".

How to get userID with json response like that?

update: I try to get with anyobject but still did not get that json string to change to dictionary.

let bodyStr = "test={ \"email\" : \"\(username)\", \"password\" : \"\(password)\" }"
let myURL = NSURL(string: Constant.getSignInEmail())!
                    let request = NSMutableURLRequest(URL: myURL)
                    request.HTTPMethod = "POST"
                    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
                    request.setValue("application/json", forHTTPHeaderField: "Accept")
                    request.HTTPBody = bodyStr.dataUsingEncoding(NSUTF8StringEncoding)!
                    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
                        (data, response, error) -> Void in
                        if let unwrappedData = data {
                            do {
                                let json:AnyObject! = try NSJSONSerialization.JSONObjectWithData(unwrappedData, options: NSJSONReadingOptions.MutableContainers) as! AnyObject
                                print("json:\(json)")
                                //let userID:String = userIDDictionary["userID"] as! String
                                //print("userID:\(userID)")
                            } catch {
                                print("Failed to get userID: \(error)")
                            }
                        }
                    }
Sarimin
  • 707
  • 1
  • 7
  • 18

4 Answers4

0

Two way you can resolve.

  1. Check your Webservice format and correct it as {"key":"value","key":"value"}
  2. or else you have to Convert NSData to NSString.

Using String(data:, encoding:.utf8)

then format the string file with reduction '\'

then again convert it to NSData type then Call JSONSerialization.

0

I think this is a case of confusion between the data that you are receiving and the way they are displayed. Either on your side, or on the server side. Try to tell us exactly what the server is sending, byte for byte.

What you have got there is a string containing JSON. Not JSON, but a string containing JSON. Which is not the same. Just like a bottle of beer is not made of beer, but of glass.

If this is indeed what you are receiving, then you should first kick the guys writing the server code. If that doesn't help, then read what the "fragment" option does; this will give you a string, then you extract the bytes, and throw the bytes into a JSON parser.

gnasher729
  • 51,477
  • 5
  • 75
  • 98
0

Try with try with NSJSONReadingOptions.AllowFragments in json reading options

Sanman
  • 1,158
  • 11
  • 23
-1

Actually this is NSASCIIStringEncoding.

For help, I created a program.

Please just copy/paste and run it. You will find your answer.

import Foundation

let string = "{\"userID\":\"dkjagfhaghdalgalg\"}"
let unwrappedData: NSData = string.dataUsingEncoding(NSASCIIStringEncoding)!

do {
let userIDDictionary:NSDictionary = try NSJSONSerialization.JSONObjectWithData(unwrappedData, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
let userid = userIDDictionary.valueForKey("userID")
print("userid:\(userid!)")


} catch {
print("Failed to get userID: \(error)")
}
Shubham Ojha
  • 461
  • 5
  • 17