有人可以帮我解决问题吗,Int的长度 我正在尝试从 JSON 中获取值。执行后,我总是得到错误是:
Error serializing json: dataCorrupted(Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "coord", intValue: nil), CodingKeys(stringValue: "lon", intValue: nil)], debugDescription: "Parsed JSON number <-77.20999999999999> does not fit in Int.", underlyingError: nil))
我的JSON:我正在尝试获取第一个节点,即"坐标">
{
"coord": {
"lon": -77.21,
"lat": 38.84
},
"weather": [
{
"id": 741,
"main": "Fog",
"description": "fog",
"icon": "50n"
},
{
"id": 701,
"main": "Mist",
"description": "mist",
"icon": "50n"
}
],
"base": "stations",
"main": {
"temp": 287.75,
"pressure": 1014,
"humidity": 77,
"temp_min": 284.15,
"temp_max": 292.15
},
"visibility": 16093,
"wind": {
"speed": 1.53,
"deg": 282.001
},
"clouds": {
"all": 1
},
"dt": 1526025120,
"sys": {
"type": 1,
"id": 3131,
"message": 0.0048,
"country": "US",
"sunrise": 1526032792,
"sunset": 1526083866
},
"id": 420039291,
"name": "Arlington",
"cod": 200
}
结构类:此类将定义对象的结构
import Foundation
struct TestingClass: Decodable{
let coord: Coord
}
struct Coord: Decodable{
let lon: Int?
let lat: Int?
}
ViewController:这个类将有一个从互联网上获取JSON的函数
。override func viewDidLoad() {
super.viewDidLoad()
initialization()
}
func initialization(){
let jsonUrlString="http://api.openweathermap.org/data/2.5/weather?zip=22003,us&appid=c632597b1892b4d415c64ca0e9fca1f1"
guard let url = URL(string: jsonUrlString) else { return }
URLSession.shared.dataTask(with: url) { (data, response, err) in
guard let data = data else { return }
do {
let courses = try JSONDecoder().decode(TestingClass.self, from: data)
print(courses.coord.lat)
} catch let jsonErr {
print("Error serializing json:", jsonErr)
}
}.resume()
}
请仔细阅读错误消息。错误非常明显
解析的 JSON 编号 <-77.209999999999999>不适合 Int
Int
表示不带小数位数的整数值。只有两种数字 JSON 类型,Int
和Double
。
坐标始终Double
struct Coord: Decodable {
let lon: Double
let lat: Double
}
注意不要将lat
和long
声明为可选,如果坐标存在,则始终包含这两个值。