2016-06-19 122 views
1

你們可以幫我創建使用ObjectMapper跟蹤JSON數據的Swift對象嗎?JSON響應數據到Swift對象[ObjectMapper]

[{ 
    "location": "Toronto, Canada",  
    "three_day_forecast": [ 
     { 
      "conditions": "Partly cloudy", 
      "day" : "Monday", 
      "temperature": 20 
     }, 
     { 
      "conditions": "Showers", 
      "day" : "Tuesday", 
      "temperature": 22 
     }, 
     { 
      "conditions": "Sunny", 
      "day" : "Wednesday", 
      "temperature": 28 
     } 
    ] 
} 
] 
+0

[生成的模型](https://gist.github.com/romainmenke/3d2b7a0ade82ade9395c15fe08353e32) –

+0

@appzYourLife結構不允許類型爲Self的屬性。所以類可以更好地表示可能發生的JSON。一個可用的初始化很難概括。有些人只需要完整數據的對象,而另一些人則不介意不完整的對象。 –

+0

這段代碼能幫助你嗎? –

回答

3

如果使用ObjectMapper

import ObjectMapper 

struct WeatherForecast: Mappable { 
    var location = "" 
    var threeDayForecast = [DailyForecast]() 

    init?(_ map: Map) { 
     // Validate your JSON here: check for required properties, etc 
    } 

    mutating func mapping(map: Map) { 
     location   <- map["location"] 
     threeDayForecast <- map["three_day_forecast"] 
    } 
} 

struct DailyForecast: Mappable { 
    var conditions = "" 
    var day = "" 
    var temperature = 0 

    init?(_ map: Map) { 
     // Validate your JSON here: check for required properties, etc 
    } 

    mutating func mapping(map: Map) { 
     conditions  <- map["conditions"] 
     day    <- map["day"] 
     temperature  <- map["temperature"] 
    } 
} 

用法:

// data is whatever you get back from the web request 
let json = try! NSJSONSerialization.JSONObjectWithData(data, options: []) 
let forecasts = Mapper<WeatherForecast>().mapArray(json)