1

I am trying to convert some obj-c code to swift specifically part that handles JSON to swift conversion.

I have a JSON string

[{"ID":"1","Field1":"666666","Field2":"111111","Field3":"1","Field4":"30"},
 {"ID":"59","Field1":"SCJtDKw","Field2":"dwdSQz8v","Field3":"1","Field4":"1"}]

How can i convert this either into Array or dictionary?

I have tried

var ProductList : NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.AllowFragments, error:&jsonerror) as NSDictionary

but this crashes on line:

0x1059ea662:  nopw   %cs:(%rax,%rax)

I have also tried converting it as an array

var ProductList : NSArray = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.AllowFragments, error:&jsonerror) as NSArray

This line gets further but then crashes on the following line (immediately after the above line)

 var ReturnValue : NSMutableArray = ProductList.objectAtIndex(0) as NSMutableArray

1 Answer 1

2

Your JSON is an array of dictionaries (the outer square brackets is the array; the curly braces represent the dictionaries). So you want the NSJSONSerialization line to be cast as array. And when you grab the first item, that's a dictionary, so you should cast it as such (not an array).

let productList = NSJSONSerialization.JSONObjectWithData(data, options: nil, error:&jsonerror) as NSArray
let returnValue = productList.objectAtIndex(0) as NSDictionary

If you want, you could use Swift array of dictionaries, too:

if let productList = NSJSONSerialization.JSONObjectWithData(data, options: nil, error:&jsonerror) as? [[String: AnyObject]] {
    let returnValue = productList[0]
    // use returnValue here
} else {
    println("JSONObjectWithData error: \(jsonerror)")
}

This second example also uses the if let optional binding to gracefully handle errors.

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.