简体   繁体   English

使用 Swift 4 中的数组解析嵌套的 JSON 语句

[英]parsing nested JSON statement with arrays in Swift 4

I looked around but could not find an answer addressing my issue.我环顾四周,但找不到解决我问题的答案。 I am new to coding and use this example to get into the subject matter.我是编码新手,并使用此示例进入主题。 I want to parse a nested JSON statement, the code I am using to test out is the following:我想解析一个嵌套的 JSON 语句,我用来测试的代码如下:

import Foundation

let jsonDict = """
{"Data":[{"id": 40, "val": 600,"valStr": "600","sysVal": "580","inst": 0,"valid": "true"},
{"id": 44, "val": 600,"valStr": "600","sysVal": "580","inst": 0,"valid": "true"}]}
""".data(using: .utf8)!
print("IF statement ")


let json = try? JSONSerialization.jsonObject(with: jsonDict, options: .allowFragments) as! [String: Any]
if let dictionary = json as? [String: Any],
    let data = dictionary["Data"]
{
    print("Data= \(data)")
}

I can access the overall content of the root element but not the elements within the array.我可以访问根元素的整体内容,但不能访问数组中的元素。 I would be really happy for any help here.我会很高兴在这里得到任何帮助。

Drop JSONSerialization and use Decodable .删除JSONSerialization并使用Decodable It's more descriptive and more efficient.它的描述性更强,效率更高。

result is the Root struct representing the outer dictionary. result是表示外部字典的Root结构。 The dictionary keys become the struct members.字典键成为结构成员。

let jsonString = """
{"Data":[{"id": 40, "val": 600,"valStr": "600","sysVal": "580","inst": 0,"valid": "true"},
{"id": 44, "val": 600,"valStr": "600","sysVal": "580","inst": 0,"valid": "true"}]}
"""

let data = Data(jsonString.utf8)

struct Root : Decodable {
    private enum CodingKeys : String, CodingKey { case data = "Data"}

    let data : [Subject]
}

struct Subject : Decodable {
    let id, val, inst : Int
    let valStr, sysVal, valid : String
}

do {
    let result = try JSONDecoder().decode(Root.self, from: data)
    for item in result.data {
        print(item.id, item.val, item.valid)
    }
} catch { print(error) }

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

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