这是我从服务器获得的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为Item
数组中的每个JSON对象创建一个items
对象。所以我想我只是循环浏览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"]))
}
我觉得这应该很容易,所以如果有人能找到我出错的地方,我真的很感激。谢谢!
答案 0 :(得分:1)
查看ObjectMapper,它是swift的另一个JSON解析器库。 它支持开箱即用地映射数组。
只需声明您的服务器响应对象,如:
class ServerResponse: Mappable {
var array: [Item]?
required init?(_ map: Map) {
}
// Mappable
func mapping(map: Map) {
array <- map["items"]
}
}
答案 1 :(得分:1)
这就是我在项目中的表现......
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)
我认为这很有用。