2016-06-19 91 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)