如何使用另一个字典格式化数据中的swift4解析json数据?

时间:2018-05-31 17:22:53

标签: json swift alamofire swift4.1 ios11.2

我正在使用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
}

enter image description here

我想访问天气词典并尝试使用最新版本的swift中的这行代码访问主键值。

我可以获得城市名称和温度但是当我实施这些代码时,我总是有警告,并且无法在天气中访问主要部分。

任何人都知道如何解决此问题吗?

enter image description here

  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)

    }

1 个答案:

答案 0 :(得分:0)

在这种情况下,问题在于代码。对于这个特定情况,swift 3和swift 4.1没有变化

我指的只是一个字典,但在json中它是一个字典数组,所以我需要强制转换为字典数组。

因此,正确的代码是:

   if let weather = dict["weather"] as? [Dictionary<String,AnyObject >]{
              if let main = weather[0]["main"] as? String {
                self._weatherType = main
                }
         }