当前位置 : 主页 > 手机开发 > 其它 >

在Swift 4中使用Decodable解析JSON

来源:互联网 收集:自由互联 发布时间:2021-06-11
有人可以帮我解决问题,Int的长度 我试图从 JSON获取值.执行后,我总是得到的错误是: Error serializing json: dataCorrupted(Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "coord", intValue: nil),
有人可以帮我解决问题,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”

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

Struct类:此类将定义对象的结构

import Foundation

struct TestingClass: Decodable{
    let coord: Coord
}

struct Coord: Decodable{
    let lon: Int?
    let lat: Int?
}

ViewController:这个类将有一个从Internet获取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()

    }
请仔细阅读错误消息.错误很明显

Parsed JSON number <-77.20999999999999> does not fit in Int

Int表示没有小数位的整数值.只有两种数字JSON类型,Int和Double.

坐标总是双倍的

struct Coord: Decodable {
    let lon: Double
    let lat: Double
}

注意不要将lat和long声明为可选,如果存在坐标,则它始终包含两个值.

网友评论