首页 > 解决方案 > 如何使用另一个字典格式数据中的 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)

    }

标签: jsonswiftalamofireswift4.1ios11.2

解决方案


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

推荐阅读