2

Can you guys help me create swift objects of using ObjectMapper of following JSON data?

[{
    "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 
        }
    ]
}
]
Mtoklitz113
  • 3,828
  • 3
  • 21
  • 40
Parion
  • 428
  • 9
  • 18

2 Answers2

4

You can reduce a lot of boilerplate code by using BetterMappable which is written over ObjectMapper using PropertyWrappers. You need to be on Swift 5.1 to use it.

Srikanth
  • 1,861
  • 17
  • 29
3

If you are using 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"]
    }
}

Usage:

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