JSON响应数据到swift对象[ObjectMapper]

时间:2016-06-19 11:24:17

标签: json swift objectmapper

你们可以帮助我创建使用以下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 
        }
    ]
}
]

2 个答案:

答案 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)

答案 1 :(得分:3)

您可以使用BetterMappable来减少很多样板代码,https://www.w3schools.com/php/php_filter.asp是使用PropertyWrappers通过ObjectMapper编写的。您需要使用Swift 5.1才能使用它。