如何快速访问项目密钥4

时间:2018-07-22 12:09:03

标签: ios arrays json swift url

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"},

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

3 个答案:

答案 0 :(得分:0)

您可以尝试

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“,”名称“:” AD DAMMAM“},{” Id“:” 1542“,”名称“:” AL BAHA“},{” Id“:” 14“, “名称”:“ AL MADINAH AL MUNAWWARAH”},{“ Id”:“ 2213”,“名称”:“ AR'AR”},{“ Id”:“ 11”,“名称”:“ BURAYDAH”}, {“ Id”:“ 10”,“名称”:“ HAIL”},{“ Id”:“ 17”,“名称”:“ JAZAN”},{“ Id”:“ 6”,“名称”:“ MAKKAH AL MUKARRAMAH“},{” Id“:” 3417“,”名称“:” NAJRAN“},{” Id“:” 3“,”名称“:” RIYADH“},{” Id“:” 2237“ ,“名称”:“ SAKAKA”},{“ Id”:“ 1”,“名称”:“ TABUK”}]}

答案 1 :(得分:0)

连同解码步骤。我添加了几个防护措施,以在出现错误时打印错误。通常,将错误抛出并在适当的级别进行处理是一种很好的做法。

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字符串转换为特定的编程语言。它使事情变得更快,更简单。

答案 2 :(得分:0)

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
}