简体   繁体   English

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

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

Here's the JSON I am getting from the server: 这是我从服务器获取的JSON:

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

Here's my Item class in Swift: 这是我在Swift中的Item类:

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

I want to create an Item object for each JSON object in the items array using SwiftyJSON. 我想使用SwiftyJSON为items数组中的每个JSON对象创建一个Item对象。 So I thought I'd just loop through the Swift array that SwiftyJSON will create for me and voila. 所以我想我只是遍历SwiftyJSON将为我和瞧创建的Swift数组。 But SwiftyJSON throws an error saying items is not an array. 但是SwiftyJSON抛出错误,指出items不是数组。 I tried subscripting it as a dictionary but you can't (I thought you could) iterate through a dictionary in a for-loop. 我尝试将其下标为字典,但是您无法(我认为可以)在for循环中遍历字典。

Here's the code I have tried: 这是我尝试过的代码:

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"]))
}

I feel like this should be pretty easy so if anyone can find where I went wrong I'd really appreciate it. 我觉得这应该很容易,所以如果有人能找到我哪里出了问题,我将非常感激。 Thanks! 谢谢!

Check out ObjectMapper , it is another JSON parser library for swift. ObjectMapper ,这是另一个用于快速处理的JSON解析器库。 It support mapping an array out of the box. 它支持开箱即用地映射数组。

Just declare your server response object like: 只需声明您的服务器响应对象即可:

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

    required init?(_ map: Map) {

    }

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

This is how i do in my project... 这就是我在项目中所做的...

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)

I think it's helpful. 我认为这很有帮助。

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

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