2

你们能帮我创建使用以下 JSON 数据的 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 
        }
    ]
}
]
4

2 回答 2

4

BetterMappable您可以通过使用 PropertyWrappers 在 ObjectMapper 上编写的代码来减少大量样板代码。您需要使用 Swift 5.1 才能使用它。

于 2020-02-28T05:03:52.727 回答
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)
于 2016-06-20T01:08:50.750 回答