2

i am using my REST Webservice to get the JSON Data i want, this works as intended and prints:

 [{
    "name": "Event1",
    "genre": "Party",
    "subtitle": "subtitle1",
    "startDate": "2015-10-10",
    "location": "Anywhere"
  },
  {
    "name": "Event2",
    "genre": "Party",
    "subtitle": "subtitle2",
    "startDate": "2015-10-10",
    "location": "Anywhere"
  }]

So this seems to be an Array with 2 Elements which are Dictionaries.

I then tried to parse the JSON with NSJSONSerialization.

let data = str.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)

        do {
            let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as! [String: AnyObject]

            if let name = json["name"] as? [String]{
                print(name)
            }
        } catch let error as NSError {
            print("Failed to load: \(error.localizedDescription)")
        }

I do get this error:

Could not cast value of type '__NSCFArray' (0x1096c1ae0) to 'NSDictionary' (0x1096c1d60).

which seems pretty clear to me, but i just don't know how to solve it.

My goal would be to create "Event" Objects from my own class.

2
  • json is a array of dictionary. With that json["name"] you're assuming it's a dictionary, which is not. So json[0]['name"]? Commented Oct 19, 2015 at 22:11
  • have you tried SwiftyJSON? Commented Oct 19, 2015 at 22:15

1 Answer 1

3

The result of the deserialization will be an array:

let data = str.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)

do {
    let dataArray = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as! NSArray

    for event in dataArray {
        print(event)
    }

} catch let error as NSError {
    print("Failed to load: \(error.localizedDescription)")
}
Sign up to request clarification or add additional context in comments.

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.