简体   繁体   中英

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:

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 . It's more descriptive and more efficient.

result is the Root struct representing the outer dictionary. 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) }

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