0

New to Swift/iphone dev ...

If I have a string in json that is an array of objs, it can start with a bracket '['. According to the json spec, afaik, this is okay. However, the following blows up as a unit test in swift/xcode:

var json = "[{\"class\":\"ProductDesign\"},{\"class\":\"ProductDesign\"}]"
let jsonObject : AnyObject! = NSJSONSerialization.JSONObjectWithData(json.dataUsingEncoding(NSUTF8StringEncoding), options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary

I've seen blog write-ups of people doing exactly this but it does not work for me (xcode does some funny stuff, popping up :

0x287784:  je     0x28778d                  ; swift_dynamicCastObjCClassUnconditional + 61
0x287786:  addl   $0x10, %esp
0x287789:  popl   %esi
0x28778a:  popl   %edi
0x28778b:  popl   %ebp
0x28778c:  retl   
0x28778d:  leal   0xea35(%esi), %eax
0x287793:  movl   0x468ef(%esi), %ecx
0x287799:  movl   %eax, 0x8(%ecx)
0x28779c:  movl   $0x0, 0xc(%ecx)
0x2877a3:  int3   
0x2877a4:  nopw   %cs:(%eax,%eax)

Any ideas? Bug in this release?? Programmer stupidity?

2
  • PLEASE go to json.org and spend the 5-10 minutes it takes to learn JSON. Then you will be a bit more able to actually code what you understand, rather than blindly copying code you don't understand. Commented Aug 19, 2014 at 1:15
  • 1
    Wow, you sir, have just earned the reputation imo as a jerk. Thanks to those that helped me understand. Commented Aug 19, 2014 at 3:12

1 Answer 1

3

Your JSON is an Array, but you're casting the result of NSJSONSerialization.JSONObjectWithData to an NSDictionary; cast it to an NSArray instead:

let jsonObject : AnyObject! = NSJSONSerialization.JSONObjectWithData(json.dataUsingEncoding(NSUTF8StringEncoding), options: NSJSONReadingOptions.MutableContainers, error: nil) as NSArray

Note: You can also exclude the AnyObject! type declaration and just do:

let jsonObject = NSJSONSerialization.JSONObjectWithData(json.dataUsingEncoding(NSUTF8StringEncoding), options: NSJSONReadingOptions.MutableContainers, error: nil) as NSArray
Sign up to request clarification or add additional context in comments.

2 Comments

And to avoid this type of issue in the future, you can use optional casting (as? instead of as)
Thanks all. Obvious once you told me.

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.