1

I'm having this issue where I can't access values from JSON response,

the response is : {"result":[true]}

and when the JSON gets it with this code

            do{

                let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)


                let result:String = json["result"]

                   print(result)


            }catch {
                print("Error with Json: \(error)")
            }

I get an error, and the when I did the debug, I saw that json had the following

how json is stored

is there anyway to access the result from json ? it didn't work treating it as an array nor as dictionary

any ideas ?

thanks

2 Answers 2

1

result is not String, it's an Array of Bool (represented by the brackets).

Basically do not annotate types unless the compiler needs them.

Cast the JSON to the proper type and use Swift native collection types. It's also recommended to use optional bindings to avoid unexpected crashes.

do {
     if let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments) as? [String:AnyObject],
          result = json["result"] as? [Bool] where !result.isEmpty {
        print(result[0])
     }

} catch {
     print("Error with Json: \(error)")
}
Sign up to request clarification or add additional context in comments.

Comments

0

Try like this

do{

            let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments) as! NSDictionary
            let result = json["result"] as! NSArray
               print(result)

            let boole = result[0];

        }catch {
            print("Error with Json: \(error)")
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.