简体   繁体   中英

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:

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

Here's my Item class in Swift:

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. So I thought I'd just loop through the Swift array that SwiftyJSON will create for me and voila. But SwiftyJSON throws an error saying items is not an array. I tried subscripting it as a dictionary but you can't (I thought you could) iterate through a dictionary in a for-loop.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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