简体   繁体   English

如何在Swift中解析JSON?

[英]How to parse JSON in Swift?

I have some JSON data that looks like this which I am trying to parse in Swift. 我有一些看起来像这样的 JSON数据,我正在尝试在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 您可以使用SwiftyJSON- https://github.com/SwiftyJSON/SwiftyJSON

or create a class based on your JSON scheme try to parse with it. 或根据您的JSON方案创建一个类,尝试对其进行解析。

like: 喜欢:

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

This snippet is not JSON. 此代码段不是JSON。 If it was JSON, the keys would be strings, like this: 如果是JSON,则密钥将是字符串,如下所示:

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

And anyway in your screenshot we see that your JSON has already been parsed ! 无论如何, 在您的屏幕截图中,我们看到您的JSON已经被解析

What you show in the image is not JSON either, but an array containing arrays and dictionaries... 您在图像中显示的也不是JSON,而是包含数组和字典的数组...


But let's say your JSON is actually valid and the missing quotes are just a copy/paste problem. 但是,可以说您的JSON实际上是有效的,缺少的引号只是一个复制/粘贴问题。

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. 然后,要实现您的目标,必须将NSJSONSerialization的结果转换为正确的JSON格式, 然后才能访问内部对象。

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)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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