JSON可解码 - 按键搜索

时间:2018-05-12 07:14:02

标签: ios json swift swift4 decodable

我正在尝试通过密钥从我的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”.schede.info_01 etc

我从链接中获取JSON

1 个答案:

答案 0 :(得分: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