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

Ios 如何使用SwiftyJSON(在Swift中)基于JSON对象数组创建对象数组?,ios,arrays,json,swift,swifty-json,Ios,Arrays,Json,Swift,Swifty Json,以下是我从服务器获得的JSON: { "items": [ { "name": "Shampoo", "price": 9 }, ... ] } 这是我在Swift中的项目课程: class Item { var name: String var price: Float init(name: String, price: Float) { s

以下是我从服务器获得的JSON:

{
    "items": [
        {
            "name": "Shampoo",
            "price": 9
        },
        ...
    ]
}
这是我在Swift中的
项目
课程:

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抛出一个错误,表示
不是数组。我试着订阅它作为一个字典,但你不能(我想你可以)在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"]))
}
我觉得这应该很容易,所以如果有人能找到我错在哪里,我会非常感激。谢谢

请查看,这是swift的另一个JSON解析器库。 它支持直接映射数组

只需声明服务器响应对象,如下所示:

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

    required init?(_ map: Map) {

    }

    // Mappable
    func mapping(map: Map) {
        array       <- map["items"]
    }
}
class服务器响应:可映射{
变量数组:[项]?
必需的初始化(umap:map){
}
//可映射
func映射(映射:映射){
数组请检查,它是swift的另一个JSON解析器库。
它支持直接映射数组

只需声明服务器响应对象,如下所示:

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

    required init?(_ map: Map) {

    }

    // Mappable
    func mapping(map: Map) {
        array       <- map["items"]
    }
}
class服务器响应:可映射{
变量数组:[项]?
必需的初始化(umap:map){
}
//可映射
func映射(映射:映射){

数组这是我在项目中的工作方式

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)

我认为这很有帮助。

这就是我在项目中的做法

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)

我认为这很有帮助。

试着打印
json[“items”]
看看它是什么?@kennytm它看起来像是一个元组,原始JSON是字符串,数组是零。检查原始JSON的格式是否正确?它与我发布的内容相同,因此如果正确,那么我的应用程序中的JSON是正确的。我觉得它与顶层是一个对象而不是数组有关,但我不知道I don’我不知道为什么会出现问题。
.arrayValue
是正确的getter吗?请尝试打印
json[“items”]
看看它是什么?@kennytm它看起来像是一个元组,原始JSON是字符串,数组是零。检查原始JSON的格式是否正确?它与我发布的内容相同,因此如果正确,那么我的应用程序中的JSON是正确的。我觉得它与顶层是一个对象而不是数组有关,但我不知道我不知道为什么会出现问题。
.arrayValue
是正确的getter吗?这很酷,但在问题解决之前我无法使用它,因为我无法从SwiftyJSON访问数据,因为当我尝试从JSON数组创建数组时,它会返回错误。它是SwiftyJSON的替代品,您应该使用它这真的很酷,但在我的问题解决之前,我无法真正使用它,因为我无法从SwiftyJSON访问数据,因为当我尝试从我的JSON数组创建数组时,它返回了一个错误。它是SwiftyJSON的替代品,你应该使用它来代替它。你可以添加你正在解析的JSON吗?这是链接并将其粘贴到JSON中Lint,您可以看到json的样子。您可以添加您正在解析的json吗?这是链接并将其粘贴到jsonLint中,您可以看到json的样子。