【问题标题】:JSON response data into swift objects [ObjectMapper]JSON 响应数据转换为 swift 对象 [ObjectMapper]
【发布时间】:2016-06-19 11:24:17
【问题描述】:

你们能帮我创建使用 ObjectMapper 的以下 JSON 数据的快速对象吗?

[{
    "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 
        }
    ]
}
]

【问题讨论】:

  • @appzYourLife 结构不允许 Self 类型的属性。因此,类更好地表示可能发生这种情况的 JSON。一个失败的初始化很难概括。有些人只想要数据完整的对象,有些人不介意不完整的对象。
  • 这段代码对你有帮助吗?
  • 你到底想在这个 JSON 中访问什么?
  • 感谢@RMenke,这确实帮助我解决了我的错误。

标签: json swift objectmapper


【解决方案1】:

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

【讨论】:

  • 哇,我正在寻找这样的解决方案,以便减少大量样板代码。谢谢@Srikanth
【解决方案2】:

如果您使用的是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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-17
    • 1970-01-01
    • 1970-01-01
    • 2018-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多