繁体   English   中英

如何使用SwiftyJSON(在Swift中)基于JSON对象数组创建对象数组?

[英]How do I create an array of objects based on array of JSON objects using SwiftyJSON (in Swift)?

这是我从服务器获取的JSON:

{
    "items": [
        {
            "name": "Shampoo",
            "price": 9
        },
        ...
    ]
}

这是我在Swift中的Item类:

class Item {
    var name: String
    var price: Float
    init(name: String, price: Float) {
        self.name = name
        self.price = price
    }
}

我想使用SwiftyJSON为items数组中的每个JSON对象创建一个Item对象。 所以我想我只是遍历SwiftyJSON将为我和瞧创建的Swift数组。 但是SwiftyJSON抛出错误,指出items不是数组。 我尝试将其下标为字典,但是您无法(我认为可以)在for循环中遍历字典。

这是我尝试过的代码:

let json = JSON(data: data) // data is the JSON from the server (above) and isn't nil
let items = json["items"].array // this is nil and where SwiftyJSON throws the error.
// error checking and optional unwrapping etc.
for item in items {
    var itemsList: [Item] = []
    itemsList.append(Item(name: item["name"], price: item["price"]))
}

我觉得这应该很容易,所以如果有人能找到我哪里出了问题,我将非常感激。 谢谢!

ObjectMapper ,这是另一个用于快速处理的JSON解析器库。 它支持开箱即用地映射数组。

只需声明您的服务器响应对象即可:

class ServerResponse: Mappable {
    var array: [Item]?

    required init?(_ map: Map) {

    }

    // Mappable
    func mapping(map: Map) {
        array       <- map["items"]
    }
}

这就是我在项目中所做的...

guard let cityName = json["city"]["name"].string else {return}
guard let cityID = json["city"]["id"].int else {return}

var allForecasts = [Forecast]()
guard let allStuff = json["list"].array else {return}

      for f in allStuff {
          guard let date = f["dt"].double else {continue}
          let dateUnix = NSDate(timeIntervalSince1970: date)
          guard let temp = f["main"]["temp"].double else {continue}
          guard let tempMin = f["main"]["temp_min"].double else {continue}
          guard let tempMax = f["main"]["temp_max"].double else {continue}
          guard let pressure = f["main"]["pressure"].double else {continue}
          guard let humidity = f["main"]["humidity"].double else {continue}
          guard let description = f["weather"][0]["description"].string else {continue}
          guard let icon = f["weather"][0]["icon"].string else {continue}
          guard let wind = f["wind"]["speed"].double else {continue}

     let weather = Forecast(temperature: temp, maximum: tempMax, minimum: tempMin, description: description, icon: icon, humidity: humidity, pressure: pressure, wind: wind, date: dateUnix)

     allForecasts.append(weather)
     }

let fullWeather = City(cityID: cityID, cityName: cityName, forecasts: allForecasts)

我认为这很有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM