用于在 swif 中解析 google distance json 的结构

问题描述 投票:0回答:1

这是 https://maps.googleapis.com/maps/api/distancematrix/json?origins=rijssen&destinations=almelo&mode=driven&language=en&key=

的 json 输出
   { "destination_addresses" : [ "Almelo, Netherlands" ],
     "origin_addresses" : [ "Rijssen, Netherlands" ],
     "rows" : [
       {
         "elements" : [
          {
             "distance" : {
              "text" : "14.1 km",
              "value" : 14090
           },
             "duration" : {
              "text" : "21 mins",
              "value" : 1267
           },
             "status" : "OK"
        }
       ]
     }
    ],
    "status" : "OK"
    }

这是 Swift 中的结构体

struct Model: Codable{
let destination_addresses : [String]
let origin_addresses : [String]
let rows : [Elements]
let status : String
  }
struct Elements: Codable {
let elements:[Distance]
  }
struct Distance: Codable{
let distance:Value
let duration:Value
let status:String
  }
struct Value: Codable{
let text:String
let value:Int
 }

这是api请求

guard let url = URL(string: api) else { return }
   URLSession.shared.dataTask(with: url) { (data, response, error) in
    do {
     if let data = data {
       let result = try JSONDecoder().decode([Model].self, from: data)

编译器错误

The data couldn’t be read because it isn’t in the correct format.

为什么代码不起作用? 谢谢你 i.a.

json swift google-distancematrix-api
1个回答
0
投票

//试试这个方法:

struct Model: 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
}
© www.soinside.com 2019 - 2024. All rights reserved.