json - 如何使用另一个字典格式数据中的 swift4 解析 json 数据?
问题描述
我正在创建一个天气预报应用程序,用于使用 API 进行学习。API 具有 Jason 格式的数据,如下所示:
{
"coord": {
"lon": 139,
"lat": 35
},
"weather": [
{
"id": 520,
"main": "Rain",
"description": "light intensity shower rain",
"icon": "09d"
}
],
"base": "stations",
"main": {
"temp": 293.15,
"pressure": 1005,
"humidity": 94,
"temp_min": 293.15,
"temp_max": 293.15
},
"visibility": 10000,
"wind": {
"speed": 7.2,
"deg": 210
},
"clouds": {
"all": 75
},
"dt": 1527753600,
"sys": {
"type": 1,
"id": 7616,
"message": 0.0068,
"country": "JP",
"sunrise": 1527708700,
"sunset": 1527760320
},
"id": 1851632,
"name": "Shuzenji",
"cod": 200
}
我想访问天气字典,并尝试在最新版本的 swift 中使用这行代码访问主键值。
我可以得到城市名称和温度但是当我实施这些代码时,我总是有错误警告并且无法在天气中访问主要。
谁能知道如何解决这个问题?
if let dict = result.value as? Dictionary< String, AnyObject>{
if let name = dict["name"] as? String {
self._cityName = name
}
if let weather = dict["weather"] as? Dictionary<String,AnyObject >{
if let main = weather[0]["main"] as? String {
self._weatherType = main
}
}
if let main = dict["main"] as? Dictionary<String, AnyObject>{
if let currentTemp = main["temp"] as? Double {
let kelvinToFarenheitPre = (currentTemp * (9/5) - 459.67)
let kelvinToFarenheit = Double( round(10 * kelvinToFarenheitPre/10 ))
self._currentTemp = kelvinToFarenheit
}
}
//print(self.cityName)
}
//print("\(dict)")
print(self.weatherType)
print(self.cityName)
}
解决方案
In this case the problem is with the code. For this specific case there is no change in swift 3 and swift 4.1
I was referring it only a dictionary but in json it is an array of dictionary so I need to cast is as the array of dictionary.
So, for this the correct code would be:
if let weather = dict["weather"] as? [Dictionary<String,AnyObject >]{
if let main = weather[0]["main"] as? String {
self._weatherType = main
}
}
推荐阅读
- r - 在拆分后如何将两个元素放入 R 中的新两个字符串向量中
- android - 保存 10 个值的最佳实践:Shared Preferences with or without JSONObject?
- google-maps - 如何让 Golang google Maps SDK NearbySearch 从多个页面返回搜索结果
- r - LuaLaTex 和 _output.yml 配置 - 基本格式错误()
- python-3.x - Python对同一类的方法使用多处理
- c# - 拖动时如何将控件保留在其父控件中?
- javascript - 当返回嵌套在 then 块中的承诺时,使用 map for Promise.all 返回未定义数组
- c# - 返回带有批处理响应的 HttpResponseMessage
- html - Typescript:从返回不稳定结果的 HTML 中获取 id 元素
- android-studio - 重复时小部件“跳过”ID号