【问题标题】:how yo access item key in swift 4如何在swift 4中访问项目密钥
【发布时间】:2018-12-30 02:09:30
【问题描述】:
if let url = URL(string: "https://mysit.com") {
    URLSession.shared.dataTask(with: url) {
        data, response, error in
        guard
            let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
            let data = data, error == nil,
            let valueEncoding = response?.textEncodingName,
            let getContent = String(data: data, encoding: valueEncoding.textEncodingToStringEncoding)
            else { return }
        print(getContent)

        }.resume()
}

我的数据

{"Regions":null,"Cities":[{"Id":"9605","Name":"YANBAA AS SENAYAH"},{"Id":"15","Name":"ABHA"},{"Id":"13","Name":"AD DAMMAM"},{"Id":"1542","Name":"AL BAHA"},{"Id":"14","Name":"AL MADINAH AL MUNAWWARAH"},{"Id":"2213","Name":"AR'AR"},{"Id":"11","Name":"BURAYDAH"},{"Id":"10","Name":"HAIL"},{"Id":"17","Name":"JAZAN"},{"Id":"6","Name":"MAKKAH AL MUKARRAMAH"},{"Id":"3417","Name":"NAJRAN"},{"Id":"3","Name":"RIYADH"},{"Id":"2237","Name":"SAKAKA"},{"Id":"1","Name":"TABUK"},

如何获取值“名称”的数组列表,你能帮帮我吗?

【问题讨论】:

  • 显示您的 JSONDecoder 代码。

标签: ios arrays json swift url


【解决方案1】:

连同解码步骤。如果出现错误,我添加了几个守卫来打印错误。抛出错误并在适当的级别进行处理通常是一种很好的做法。

func work() {
    guard let url = URL(string: "https://mysit.com") else {
        fatalError("url is nil.")
    }

    URLSession.shared.dataTask(with: url) {
        data, response, error in
        guard error == nil else {
            fatalError("\(error!)")
        }
        guard let response = response as? HTTPURLResponse,
            response.statusCode == 200 else {
            fatalError("Response is nil.")
        }
        guard let data = data else {
            fatalError("data is nil.")
        }

        decode(data: data)

    }.resume()
}

func decode(data: Data) {
    let decoder = JSONDecoder.init()
    let welcome = try! decoder.decode(Welcome.self, from: data)

    print(welcome.cities.first!)
}

解码助手。 enum CodingKeys 用于将小写属性转换为大写 JSON 属性并返回。

struct Welcome: Codable {
    var regions: [Region]?
    let cities: [City]

    enum CodingKeys: String, CodingKey {
        case regions = "Regions"
        case cities = "Cities"
    }
}

struct City: Codable {
    let id, name: String

    enum CodingKeys: String, CodingKey {
        case id = "Id"
        case name = "Name"
    }
}

struct Region: Codable {
    let id, name: String

    enum CodingKeys: String, CodingKey {
        case id = "Id"
        case name = "Name"
    }
}

有些人使用Quicktype 等服务将 JSON 字符串转换为特定的编程语言。它使事情变得更快、更简单。

【讨论】:

  • 从 url JSON 获取数据
【解决方案2】:
let responseData = try JSONSerialization.jsonObject(with: (response["Cities"] as! String).data(using: String.Encoding.utf8)!, options: []) as! [[String: Any]]

for item in responseData{
  let name =  item["Name"] as! String
}

【讨论】:

    【解决方案3】:

    你可以试试

    struct Root :Decodable{
    
        let Cities:[InnerItem]
    
    }
    
    struct InnerItem :Decodable{
    
        let Id:String
    
        let Name:String
    
    }
    
    do {
    
        let arr = try JSONDecoder().decode(Root.self, from: data)
    
        print(arr.Cities)
    }
    catch {
    
        print(error)
    }
    

    //

    注意:这是正确的json结构

    {"Regions":null,"Cities":[{"Id":"9605","Name":"YANBAA AS SENAYAH"},{"Id":"15","Name":"ABHA "},{"Id":"13","Name":"AD DAMMAM"},{"Id":"1542","Name":"AL BAHA"},{"Id":"14", "姓名":"AL MADINAH AL MUNAWWARAH"},{"Id":"2213","姓名":"AR'AR"},{"Id":"11","姓名":"BURAYDAH"}, {"Id":"10","Name":"HAIL"},{"Id":"17","Name":"JAZAN"},{"Id":"6","Name":" MAKKAH AL MUKARRAMAH"},{"Id":"3417","Name":"NAJRAN"},{"Id":"3","Name":"RIYADH"},{"Id":"2237" ,"姓名":"SAKAKA"},{"Id":"1","姓名":"TABUK"}]}

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-28
      • 1970-01-01
      • 1970-01-01
      • 2018-05-28
      • 1970-01-01
      • 2013-05-11
      • 2017-10-02
      相关资源
      最近更新 更多