2

I need to get string from the JSON Array which is a response from the external server. This is my code:

if let dictionary = NSJSONSerialization.JSONObjectWithData(data,options: NSJSONReadingOptions.MutableContainers,error: &parsingError) as NSDictionary?{

    var info : NSArray = dictionary.valueForKey("data") as NSArray
    var names: String? = info[0].valueForKey("firstname") as? String

    println("name ++\(names)")

}

It's compiling but when I execute, not running I got as

thread 8:exc_bad_access (code=2 ..

This is Dictonary coming from server side

{
 data =     {
     Id = 55;
     firstName = fgg;
     gender = 1;
 };
 success = 1; }

I followed thread without success : Getting Values from JSON Array in Swift

Can anyone help me to get this string out? I cannot find out the error I have done here. Any help would be appreciated.

5
  • 2
    Its not an array, its a dictionary. Commented Dec 20, 2016 at 12:30
  • Try this var info : NSDictionary = dictionary.valueForKey("data") as NSDictionary var names: String? = info["firstName"] as? String println("name ++\(names)") Commented Dec 20, 2016 at 12:36
  • please let me know if any issue occur Thanks! Commented Dec 20, 2016 at 12:40
  • @MuseerAnsari Thanks. It's working but print with "Optional". Can you add this as a answer so I can accept it. Commented Dec 20, 2016 at 13:09
  • Yes just copy and paste my answer (given below) i have updated and if working then please upvote Thank You! Commented Dec 20, 2016 at 13:12

3 Answers 3

1

Try this

if let dictionary = NSJSONSerialization.JSONObjectWithData(data,options: NSJSONReadingOptions.MutableContainers,error: &parsingError) as NSDictionary?{

    var info : NSDictionary = dictionary.valueForKey("data") as! NSDictionary 
    var names: String? = info["firstName"] as? String 
    println("name ++\(names!)")

}
Sign up to request clarification or add additional context in comments.

Comments

0
let dataId = response.value(forKeyPath: "data.id") as! NSNumber

I usually do this if am not up to deserialization.

1 Comment

Thanks for you support.
0

Try this :

do
{
 let data = try JSONSerialization.data(withJSONObject: json, options: JSONSerialization.WritingOptions.prettyPrinted)
}
catch _{}

let data      = json["data"] as! NSDictionary
let firstName = data["firstName"]

1 Comment

Thanks for you support.

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.