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 
        }
    ]
}
]
5
  • generated model Commented Jun 19, 2016 at 11:50
  • @appzYourLife Structs don't allow attributes of type Self. So classes are better to represent JSON where that might happen. A failable init is hard to generalise. Some people want only the objects with complete data, others don't mind incomplete objects. Commented Jun 19, 2016 at 11:54
  • Did that code help you out? Commented Jun 19, 2016 at 12:22
  • What exactly do you want to access in this JSON? Commented Jun 19, 2016 at 13:08
  • 1
    Thanks @RMenke , That did help me sort out my mistake. Commented Jun 20, 2016 at 7:03

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Wow, I was finding a solution like this so that it reduces lots of boilerplate code. Thanks @Srikanth
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.