在Swift 4中使用Decodable解析JSON

在Swift 4中使用Decodable解析JSON,第1张

概述有人可以帮我解决问题,Int的长度 我试图从 JSON获取值.执行后,我总是得到的错误是: Error serializing json: dataCorrupted(Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "coord", intValue: nil), CodingKeys(stringValue: "l 有人可以帮我解决问题,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 Foundationstruct 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()    }
解决方法@H_404_35@ 请仔细阅读错误消息.错误很明显

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声明为可选,如果存在坐标,则它始终包含两个值.

总结

以上是内存溢出为你收集整理的在Swift 4中使用Decodable解析JSON全部内容,希望文章能够帮你解决在Swift 4中使用Decodable解析JSON所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/web/1005748.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-22
下一篇 2022-05-22

发表评论

登录后才能评论

评论列表(0条)

保存