2016-06-22 6 views
1

に、アレイ内のアレイからJSONデータを抽出します。あなたは、このサンプルからわかるように、リストの下にあり、多くのオブジェクトがあり、私がしたいことはただ一時、天候あるは、どのように私は現在、天気予報情報を取得するためにOpenweathermap.orgを使用していスウィフト2.0

{ 
 
    "city":{ }, 
 
    "cod":"200", 
 
    "message":0.0029, 
 
    "cnt":40, 
 
    "list":[ 
 
     { 
 
     "dt":1466532000, 
 
     "main":{ 
 
      "temp":296.52, 
 
      "temp_min":294.864, 
 
      "temp_max":296.52, 
 
      "pressure":1004.95, 
 
      "sea_level":1023.45, 
 
      "grnd_level":1004.95, 
 
      "humidity":58, 
 
      "temp_kf":1.65 
 
     }, 
 
     "weather":[ 
 
      { 
 
       "id":803, 
 
       "main":"Clouds", 
 
       "description":"broken clouds", 
 
       "icon":"04d" 
 
      } 
 
     ], 
 
     "clouds":{ }, 
 
     "wind":{ }, 
 
     "sys":{ }, 
 
     "dt_txt":"2016-06-21 18:00:00" 
 
     }, 
 
     { 
 
     "dt":1466542800, 
 
     "main":{ }, 
 
     "weather":[ ], 
 
     "clouds":{ }, 
 
     "wind":{ }, 
 
     "sys":{ }, 
 
     "dt_txt":"2016-06-21 21:00:00" 
 
     }, 
 
     { 
 
     "dt":1466553600, 
 
     "main":{ }, 
 
     "weather":[ ], 
 
     "clouds":{ }, 
 
     "wind":{ }, 
 
     "sys":{ }, 
 
     "dt_txt":"2016-06-22 00:00:00" 
 
     }] 
 
}

:そしてここで私は彼らのAPIから得たJSONオブジェクトでありますメインと説明。 JSONオブジェクトのすべてをソートして保持するためにStructを作成しましたが、エラーが表示され続けます。どのように "dt"の観点からソートし、JSONからデータを抽出するのですか?ありがとう。

は、ここに私の構造体である:

import Foundation 

struct FutureWeather { 

//future stuff 
var futureDt: NSDate // 
var futureMainWeather: String// 
var futureDescription: String// 
private var futureTemp: Double// 
var futureTempCelsius: Double { 
    get { 
     return futureTemp - 273.15 
    } 
} 
var futureTempFahrenheit: Double { 
    get { 
     return (futureTemp - 273.15) * 1.8 + 32 
    } 
} 


init(futureWeatherData : [String:AnyObject]) { 

    //first set of data 
    let futureWeatherDictUno = futureWeatherData["list"]![0] as! [String: AnyObject] 
    print(futureWeatherDictUno) 

    let events = futureWeatherDictUno.sort({$0["dt"] < $1["dt"]}) 

    futureDt = NSDate(timeIntervalSince1970: futureWeatherDictUno["dt"] as! NSTimeInterval) 

    let mainDictOne = futureWeatherDictUno["main"] as! [String: AnyObject] 
    futureTemp = mainDictOne["temp"] as! Double 

    let weatherDictOne = futureWeatherDictUno["weather"]![0] as! [String: AnyObject] 
    futureMainWeather = weatherDictOne["main"] as! String 
    futureDescription = weatherDictOne["description"] as! String 


    //the second set of data 
    let futureWeatherDictDos = futureWeatherData["list"]![1] as! [String: AnyObject] 
    futureDt = NSDate(timeIntervalSince1970: futureWeatherDictUno["dt"] as! NSTimeInterval) 

    let mainDictTwo = futureWeatherDictDos["main"] as! [String: AnyObject] 
    futureTemp = mainDictTwo["temp"] as! Double 

    let weatherDictTwo = futureWeatherDictDos["weather"]![0] as! [String: AnyObject] 
    futureMainWeather = weatherDictTwo["main"] as! String 
    futureDescription = weatherDictTwo["description"] as! String 


    } 

} 
+0

うーん...何のエラーを取得するために、将来の前に、ここでこの答えを投稿していますか? – Alexander

答えて

1

あなたはそれぞれの要素がすでに要素dtに基づいてJSONファイルにソートされなければならないlist配列を通過します。あなたはそれを並べ替えることはできませんので、また、アレイ内の各要素(futureWeatherData["list"]![0])は一つだけdtのキー/値を持つことになります。あなたは何をすべき

は(これは単なる擬似コードである)があるで次

let futureWeather = [Weather]() 
for element : JSON in array { 
    let weather = Weather(json: element) //create weather element from json 
    futureWeather.append(weather) 
} 

何をする必要はありませんが、あなたのinitメソッドでは、手動でリスト内の各要素を通過していますあなたのFutureWeatherクラスで。

私もhttps://github.com/SwiftyJSON/SwiftyJSONを使用してJSONを通過する列挙型のキーを作成するに探してお勧めします。

0

@Asdrubalは、彼らの回答SwiftyJSONで指摘したように便利なライブラリです。純粋なFoundationソリューションが必要な場合は、NSJSONSerializationを使用してAPIデータからの応答を得ることができます。私は、個人的なサーバー側スウィフトプロジェクトは、気象データ:)

import Foundation 

enum WeatherError: Int, ErrorType { 
    /// The API response text could not be converted to an 
    /// NSData object using NSUnicodeStringEncoding 
    case UnexpectedAPITextEncoding = 1 

    /// The API reponse object did not contain an array of 
    /// Dictionary<String, AnyObject> objects at the "list" 
    /// key 
    case UnexpectedAPIResponseFormat = 2 
} 

/// An abstraction of a response to the OpenWeatherMap.org forecast API. 
/// Contains only date, description and temperature data, plus convenience 
/// properties to display temp in F or C. 
/// 
/// NOTE: Each of the properties on the value are Optional, reflecting the 
/// fact that the API response is sparsely populated for many of its values. 
struct OpenWeatherMapResponse { 

    /// The date of the forecast. Could be in the future 
    let futureDt: NSDate? 

    /// Textual description of the weather conditions for the forecast time 
    let futureDescription: String? 

    /// Temp provided in K 
    private let futureTemp: Double? 

    /// Temperature for the forecast time, in degrees C 
    var futureTempCelsius: Double? { 
     get { 
      guard let futureTemp = futureTemp else { 
       return nil 
      } 
      return futureTemp - 273.15 
     } 
    } 

    /// Temperature for the forecast time, in degrees F 
    var futureTempFahrenheit: Double? { 
     get { 
      guard let futureTemp = futureTemp else { 
       return nil 
      } 
      return (futureTemp - 273.15) * 1.8 + 32 
     } 
    } 

    /// Given a member of `list` from the API response, 
    /// creates an OpenWeatherMapResponse 
    init(jsonObject: AnyObject) { 
     if let timestamp = jsonObject["dt"] as? NSTimeInterval { 
      futureDt = NSDate(timeIntervalSince1970: timestamp) 
     } else { 
      futureDt = nil 
     } 

     if let mainBlock = jsonObject["main"] as? [String: AnyObject], 
      temp = mainBlock["temp"] as? Double { 
      futureTemp = temp 
     } else { 
      futureTemp = nil 
     } 

     if let weatherList = jsonObject["weather"] as? [AnyObject], 
      description = weatherList.first?["description"] as? String { 
      futureDescription = description 
     } else { 
      futureDescription = nil 
     } 
    } 

    /// Given a JSON Object converted from an API response, parse the object 
    /// into a collection of FutureWeather values. 
    /// - throws: WeatherError if the API response text is in an unexpected character encoding or in 
    /// an unexpected format 
    /// - returns: an array of OpenWeatherMapResponse values 
    static func responsesByConvertingAPIResponseString(apiResponseString: String) throws -> [OpenWeatherMapResponse] { 

     // NSJSONSerialization only works on NSData. Convert it before using 
     guard let apiData = apiResponseString.dataUsingEncoding(NSUnicodeStringEncoding) else { 
      throw WeatherError.UnexpectedAPITextEncoding 
     } 

     // Convert API response data to a Foundation AnyObject 
     let jsonObject = try NSJSONSerialization.JSONObjectWithData(apiData, options: []) 

     var weatherList = [OpenWeatherMapResponse]() 

     guard let events = jsonObject["list"] as? [[String: AnyObject]] else { 
      throw WeatherError.UnexpectedAPIResponseFormat 
     } 

     for event in events { 
      weatherList.append(OpenWeatherMapResponse(jsonObject: event)) 
     } 

     return weatherList 
    } 

} 


// API response 
let jsonString = "{ \"city\":{ }, \"cod\":\"200\", \"message\":0.0029, \"cnt\":40, \"list\":[ { \"dt\":1466532000, \"main\":{ \"temp\":296.52, \"temp_min\":294.864, \"temp_max\":296.52, \"pressure\":1004.95, \"sea_level\":1023.45, \"grnd_level\":1004.95, \"humidity\":58, \"temp_kf\":1.65 }, \"weather\":[ { \"id\":803, \"main\":\"Clouds\", \"description\":\"broken clouds\", \"icon\":\"04d\" } ], \"clouds\":{ }, \"wind\":{ }, \"sys\":{ }, \"dt_txt\":\"2016-06-21 18:00:00\" }, { \"dt\":1466542800, \"main\":{ }, \"weather\":[ ], \"clouds\":{ }, \"wind\":{ }, \"sys\":{ }, \"dt_txt\":\"2016-06-21 21:00:00\" }, { \"dt\":1466553600, \"main\":{ }, \"weather\":[ ], \"clouds\":{ }, \"wind\":{ }, \"sys\":{ }, \"dt_txt\":\"2016-06-22 00:00:00\" }] }" 

let weatherEvents = try OpenWeatherMapResponse.responsesByConvertingAPIResponseString(jsonString) 

let sortedWeatherEvents = weatherEvents.sort() { a, b in a.futureDt?.timeIntervalSince1970 < b.futureDt?.timeIntervalSince1970 } 

// prints: 
// event: OpenWeatherMapResponse(futureDt: Optional(2016-06-21 18:00:00 +0000), futureDescription: Optional("broken clouds"), futureTemp: Optional(296.51999999999998)) 
// event: OpenWeatherMapResponse(futureDt: Optional(2016-06-21 21:00:00 +0000), futureDescription: nil, futureTemp: nil) 
// event: OpenWeatherMapResponse(futureDt: Optional(2016-06-22 00:00:00 +0000), futureDescription: nil, futureTemp: nil) 
for event in sortedWeatherEvents { 
    print("event: \(event)") 
} 
関連する問題