简体   繁体   中英

How to parse JSON in Swift?

I have some JSON data that looks like this which I am trying to parse in Swift.

[
  [
    {
        a: "1",
        b: "2"
    },
    [
        {
            c: "3",
        },
        {
            d: "4",
        }
    ]
 ]

]

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

        if let myArray = json[0] as? [[AnyObject]] {
            for myObject in myArray {
                print("This works!\(myObject)")
            }
        }

However nothing I try seems to work - any help would be appreciated.

you can use SwiftyJSON - https://github.com/SwiftyJSON/SwiftyJSON

or create a class based on your JSON scheme try to parse with it.

like:

class object
{
  let data = Array<subObject>()
}
class subObject
{
  let subData = Array<Dictionary<AnyObject,AnyObject>>()
}

This snippet is not JSON. If it was JSON, the keys would be strings, like this:

[
  [
    {
        "a": "1",
        "b": "2"
    },
    [
        {
            "c": "3",
        },
        {
            "d": "4",
        }
    ]
 ]
]

And anyway in your screenshot we see that your JSON has already been parsed !

What you show in the image is not JSON either, but an array containing arrays and dictionaries...


But let's say your JSON is actually valid and the missing quotes are just a copy/paste problem.

Then to achieve your goal you have to cast the result of NSJSONSerialization to the correct JSON format, then you can access the inner objects.

Like this, for example:

do {
    if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [[AnyObject]] {
        if let myArray = json.first {
            for myObject in myArray {
                print("This works!\(myObject)")
            }
        }
    }
} catch let error as NSError {
    print(error.localizedDescription)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM