json - 如何获取嵌套在 NSDictionary 字典中的值?

标签 json swift

如果标题不清楚,我深表歉意。我不太确定 NSDictionary 和 JSON 究竟是如何工作的。

我正在尝试使用 Swift 制作一个简单的应用程序,它从 .JSON 文件中获取值,并将它们打印到控制台。这是我的 JSON 文件:

{

"students": [
    {
        "name": "Stew Dent",
        "age": "10",
        "year": 6,
        "grades": [
            {
                "english": "a-plus",
                "math": "b-plus"
            },
            {
                "english": "a",
                "math": "a-minus"
            }
        ]

    },

    {
        "name": "Mary Brown",
        "age": "14",
        "year": 10,
        "grades": [
            {
                "english": "a-plus",
                "math": "a-plus"
            },
            {
                "english": "a-plus",
                "math": "a"
            }
        ]

    }
]

}

目前,我能够检索除“成绩”中的值以外的所有值。这是我的 Swift 代码:

if let path = Bundle.main.path(forResource: "school", ofType: "json")
    {
        do {
            // Retrieve data from JSON file
            let jsonData = try NSData(contentsOfFile: path, options: .mappedIfSafe)

            // Convert data into NSDictionary
            let jsonResult = try JSONSerialization.jsonObject(with: jsonData as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary



            if let students : [NSDictionary] = jsonResult?["students"] as? [NSDictionary]
            {
                if let grades : [NSDictionary] = students["grades"] as? [NSDictionary]
                {
                    for grade: NSDictionary in grades
                    {
                        for (subject, gradevalue) in grade
                        {
                            print ("\(subject): \(gradevalue)")
                        }

                    }
                }



            }



        } catch
        {

        }


    }

如果我没记错的话,“成绩”是“学生”字典里面的一个字典。但是,它无法运行上面的代码。在“if let grades...”行中,它给出了错误消息:“无法为索引类型为‘String’的‘[NSDictionary]’类型的值下标。

那我做错了什么?甚至有什么方法可以检索这些值吗?我错过了什么吗?任何帮助将不胜感激。谢谢:)

最佳答案

您应该使用 Swift 原生类型 Data 而不是 NSData 和 Dictionary [String:Any] 而不是 NSDictionary。您还忘记遍历每个学生。像这样尝试:

do {
    if let dict = try JSONSerialization.jsonObject(with: jsonData) as? [String: Any] {
        print(dict)
        if let students = dict["students"] as? [[String: Any]] {
            print(students)
            for student in students {
                print(student["name"] ?? "")
                if let grades = student["grades"] as?  [[String: Any]] {
                    for grade in grades {
                        for (subject, gradevalue) in grade {
                            print ("student:",student["name"] ?? "", "subject:", subject, "grade:", gradevalue)
                        }
                    }
                }
            }
        }
    }
} catch {
    print(error)
}

关于json - 如何获取嵌套在 NSDictionary 字典中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42264031/

相关文章:

java - 将 JSONObject 发送到 URL

swift - 从类根到 init 内部,再到 touchesBegan 内部的作用域?

Swift 扩展协议(protocol)

ios - 如何使用 iOS Compression Framework 压缩多个文件?

ios - 启用分页时 UICollectionView 使隐藏单元出列

C# 使用 JSON.Net 解析 JSON 数字属性

java - 使用 PagedResources/嵌入对象反序列化日期。 jackson . Spring

json - 如何在 elm-core > 5.0.0 的 Json.Decoder 中从 String 转换为 Int

javascript - 如何将正则表达式从数组传递到字符串,当使用 .join ('' 时)例如 ["X","-","M","E","N"]

ios - 为自定义 Scenekit 渲染匹配 ARSCNView 转换?