如何从JSON响应中检索特定数据?

时间:2018-08-05 11:03:07

标签: ios json swift4 google-distancematrix-api

当前,我正在使用Google Maps距离矩阵API,并在运行以下代码时得到以下结果:

func configureRoute(origin:String,destination:String){
    let jsonURL = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=place_id:\(origin)&destinations=place_id:\(destination)&key=MYAPIKEY"
    guard let url = URL(string: jsonURL ) else {return}

    URLSession.shared.dataTask(with: url) { (data, response, err) in

        guard let data = data else {return}

        let dataAsString = String(data: data, encoding: .utf8)
        print(dataAsString)
        }.resume()
    }

这是结果:

Optional("{\n   \"destination_addresses\" : [ \"Pittsburgh, PA, USA\" ],\n   \"origin_addresses\" : [ \"Philadelphia, PA, USA\" ],\n   \"rows\" : [\n      {\n         \"elements\" : [\n            {\n               \"distance\" : {\n                  \"text\" : \"305 mi\",\n                  \"value\" : 490750\n               },\n               \"duration\" : {\n                  \"text\" : \"4 hours 48 mins\",\n                  \"value\" : 17257\n               },\n               \"status\" : \"OK\"\n            }\n         ]\n      }\n   ],\n   \"status\" : \"OK\"\n}\n")

但是从这个结果中,我只想得到距离的持续时间,在这种情况下,距离是4小时48分钟。我怎么会得到持续时间?

尝试一些建议后,我放置了JSON url以获取格式化的结构,并得到以下结果:

struct Welcome: Codable {
let destinationAddresses, originAddresses: [String]
let rows: [Row]
let status: String

enum CodingKeys: String, CodingKey {
    case destinationAddresses = "destination_addresses"
    case originAddresses = "origin_addresses"
    case rows, status
}
}

struct Row: Codable {
let elements: [Element]
 }

struct Element: Codable {
let distance, duration: Distance
let status: String
}

struct Distance: Codable {
let text: String
let value: Int
 }

使用此代码,我实现了以下代码:

func configureRoute(origin:String,destination:String){
    let jsonURL = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=place_id:\(origin)&destinations=place_id:\(destination)&key=MYAPIKEY"
    guard let url = URL(string: jsonURL ) else {return}
    print(jsonURL)

    URLSession.shared.dataTask(with: url) { (data, response, err) in

        guard let data = data else {return}

        do{
            let route = try JSONDecoder().decode(Element.self, from: data)
            print (route.duration)
        }
        catch let jsonErr{

        }
        let dataAsString = String(data: data, encoding: .utf8)
//            print(dataAsString)
        }.resume()
}

但是我对route.duration的结果仍然没有。

2 个答案:

答案 0 :(得分:1)

  1. 接受您的JSON响应并将其粘贴到以下在线json中,以快速进行结构转换器。 JSON String to Swift struct converter

    {
    "name": "John",
    "age": 31,
    "city": "New York"
    }
    
  2. 现在复制生成的结构。

    struct JSON: Codable {
     let name: String
     let age: Int
     let city: String
    }
    
  3. 解码您的数据响应。不要忘记尝试catch和错误处理

    let jsonRespone:JSON = try JSONDecoder().decode(JSON.self, data);
    
  4. 现在,您可以使用结构访问数据了。如果您的JSON响应中包含的信息并不总是存在(例如错误消息),只需将JSON Struct或特定键设置为可选。

    let cityName:String = jsonResponse.city
    let age:Int = jsonResponse.age
    let name:String = jsonResponse.name
    

答案 1 :(得分:-1)

使用SwiftyJSON:

导入SwiftyJSON

func configureRoute(origin:String,destination:String){
    let jsonURL = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=place_id:\(origin)&destinations=place_id:\(destination)&key=MYAPIKEY"
    guard let url = URL(string: jsonURL ) else {return}

    URLSession.shared.dataTask(with: url) { (data, response, err) in

        guard let data = data else {return}

        let dataAsString = String(data: data, encoding: .utf8)
        if let json = JSON(data: data){
            if let durationValue = json["rows"][0]["elements"][0]["duration"]["value"].int32 {
            //This is duration seconds, 17257
        }

        if let durationText = json["rows"][0]["elements"][0]["duration"]["text"].stringValue {
           //this is duration text, 4 hours 48 mins
        }
        print(dataAsString)
        }.resume()
    }