首页 文章

JSON可解码 - 按键搜索

提问于
浏览
0

我正在尝试做一些代码来通过密钥从我的JSON获取信息 .

JSON看起来像:

{
  "Test Name": {
    "schede": {
      "info_01": "Info 01",
      "info_02": "Info 02",
      "info_03": "Info 03",
      "info_04": "Info 04",
      "info_05": "Info 05"
      },
    "Info" : "info"
  }
}

我希望在应用程序启动时下载JSON . JSON被解码,我想创建一个传递密钥的函数,它将打印我需要的所有信息,如schede.info_01或JSON上的信息字符串 . 它就像一个可解码的JSON

我的JSON中的关键是:“Test Name”然后如果你传入函数字符串'Test Name',它将打印每个结果,如:“Test Name”.schede.info_01等

我从链接获取JSON

1 回答

  • 1

    首先从json创建数据模型:

    struct MyData: Codable {
        let testName: TestName
    
        enum CodingKeys: String, CodingKey {
            case testName = "Test Name"
        }
    }
    
    struct TestName: Codable {
        let schede: [String: String]
        let info: String
    
        enum CodingKeys: String, CodingKey {
            case schede
            case info = "Info"
        }
    }
    

    如果您不确定您的JSON将始终具有特定值,则可以将属性设置为可选 .

    然后创建一个获取数据并解析它的函数:

    func getData(url: URL, completion: @escaping (_ data: MyData?, _ error: Error?) -> ()) {
        let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
            guard let receivedData = data else {
                completion(nil, error)
                return
            }
    
            do {
                // Check if there is a valid json object and parse it with JSONDecoder
                let object = try JSONDecoder().decode(MyData.self, from: receivedData)
                completion(object, nil)
            } catch {
                completion(nil, error)
            }
        }
        task.resume()
    }
    

    并调用您的函数:

    getData(url: URL(string: "https://yourexampleurl.com/myData")!) { (data, error) in
            // if you want to use the received data in the UI
            // you need to dispatch it back to the main thread
            // because dataTask executes it not on the main thread (by default)
            DispatchQueue.main.async {
                if let info1 = data?.testName.schede["info_01"] {
                    print("received mt info: \(info1)")
                } else {
                    let errorMessage = error?.localizedDescription ?? "unknown error"
                    print("error occured: \(errorMessage)")
                }
            }
        }
    

    因为您将json结构映射到Swift对象,所以您可以使用点运算符访问您的数据:

    let info1 = data.testName.schede["info_01"]
    

    您可以一直为 Schede 对象创建模型,然后将其解析为字典,您可以访问以下值:

    let info1 = data.testName.schede.info1
    

相关问题