2016-12-09 110 views
1

我在swift 3中編寫代碼,用於解析來自http請求的json格式結果中的查詢。SwiftyJSON解析json查詢

JSON格式是:

JSON: { 
base = stations; 
coord =  { 
    lat = "23.9"; 
    lon = "42.89"; 
}; 
weather =  (
      { 
     description = mist; 
     icon = 50n; 
     id = 701; 
     main = Mist; 
    }, 
      { 
     description = fog; 
     icon = 50n; 
     id = 741; 
     main = Fog; 
    } 
); 
wind =  { 
    deg = "222.506"; 
    speed = "1.72"; 
};} 

我的代碼是:

Alamofire.request(url).responseJSON { response in 

     if let a = response.result.value { 

      let jsonVar = JSON(a) 

      if let resDati = jsonVar["base"].string { 
       print(resDati as String) // <- OK 
      } 

      if let dati2 = jsonVar["weather"].array { 

       for item in dati2 { 

        print(" > \(item["main"])") // <- OK 

       } 

      } 

     } else { 
      print(Error.self) 
     } 

    } 

的問題是在 「座標」 和 「風」 的數據,我有嘗試:

if let dati4 = jsonVar["wind"].array { 

    for item in dati4 { 

     print("-- \(item)") 

    } } 

我無法打印JSON格式的「風」和「協調」數據親戚。

我該如何解決這個問題。

謝謝。

回答

2

關鍵wind包含一個字典,而不是一個數組,你可以用這個代碼獲得使用SwiftyJSON的degspeed值:

if let wind = jsonVar["wind"].dictionary, 
    let deg = wind["deg"]?.double, 
    let speed = wind["speed"]?.double { 
    print(deg, speed) 
} 

coord作品相應

if let coord = jsonVar["coord"].dictionary, 
    let lat = coord["lat"]?.double, 
    let lon = coord["lon"]?.double { 
    print(lat, lon) 
} 

注:所有的值是Double,類型的json格式是有誤導性的。

+0

我寫了你的代碼,但'deg'和'speed'的結果是零。 –

+0

如果'jsonVar [「base」]'輸出了一些內容('< - OK'),我的代碼應該可以工作。太。 – vadian

+0

我已經添加了你的代碼在我的和控制檯它打印'基'和'天氣',但不是'風',所以我已經轉移'讓deg'和'讓速度'從'如果'和控制檯我看到'零無'。 –