【发布时间】:2020-01-28 07:05:39
【问题描述】:
我是 Swift 的新手。我想使用 url 从服务器获取一些 json 数据。我尝试了许多其他解决方案,但没有奏效。我想从数组中打印duration 键(文本和值),然后在控制台中打印。
Json 数据附在下方
{
"status": "OK",
"rows": [
{
"elements": [
{
"duration": {
"text": "3 hours 49 mins",
"value": 13725
},
"distance": {
"text": "225 mi",
"value": 361715
},
"status": "OK"
}
]
}
],
"origin_addresses": [
"Washington, DC, USA"
],
"destination_addresses": [
"New York, NY, USA"
]
}
附加代码
func getdatajson1(){
if let url = URL(string: "http://www.json-generator.com/api/json/get/bQywstyfkO?indent=2") {
URLSession.shared.dataTask(with: url) { data, response, error in
if let data = data {
do {
let res = try JSONDecoder().decode(Root.self, from: data)
print(res.rows)
} catch let error {
print(error)
}
}
}.resume()
}
}
struct Root: Codable {
let rows: [Root2]
}
struct Root2: Codable {
let elements: [Root3]
}
struct Root3: Codable {
let elements: [node]
}
struct node: Codable {
let duration : [valuesarray]
}
struct valuesarray: Codable {
let text : String
let value : Int
}
【问题讨论】:
-
什么是打印
res.rows这个语句? -
什么都没有!!它的代码错误
-
是打印
nil还是别的什么? -
找不到它的打印密钥
-
“未找到其打印密钥”。然后它正在打印`print(error)`,但是请阅读该错误,或者如果您不理解它,请将其添加到您的问题中,它包含有关问题的重要信息。
标签: ios json swift xcode decode