【问题标题】:Parsing JSON using Decodable in Swift 4在 Swift 4 中使用 Decodable 解析 JSON
【发布时间】:2018-10-21 17:24:13
【问题描述】:

谁能帮我解决这个问题,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
}

Struct Class:这个类将定义一个对象的结构

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()

    }

【问题讨论】:

    标签: json swift4 decodable


    【解决方案1】:

    请仔细阅读错误信息。错误很明显

    解析的 JSON 数字 不适合 Int

    Int 表示没有小数位的整数值。只有两种数字 JSON 类型,IntDouble

    坐标始终为Double

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

    注意不要将latlong 声明为可选,如果坐标存在,则它始终包含这两个值。

    【讨论】:

    • 谢谢 Vadian,我明白了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-19
    • 1970-01-01
    • 1970-01-01
    • 2018-04-10
    • 2018-08-23
    相关资源
    最近更新 更多