2016-07-24 68 views
0

下面是我从服务器获取JSON:如何使用SwiftyJSON(在Swift中)基于JSON对象数组创建一个对象数组?

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

这里是我的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"])) 
} 

我觉得这应该是很容易,所以如果任何人都可以找到,我出了问题我会很感激。谢谢!

+0

尝试打印'json [“items”]'看看它是什么? – kennytm

+0

@kennytm它看起来像一个元组,原始JSON作为一个字符串和数组,它是零。 – Jake

+0

检查原始JSON格式是否正确? – kennytm

回答

1

检出ObjectMapper,这是另一个用于swift的JSON解析器库。 它支持将数组映射到盒子外面。

只需申报您的服务器响应的对象,如:

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

    required init?(_ map: Map) { 

    } 

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

这真的很酷,但我不能真正使用它,直到我的问题得到解决,因为我无法从SwiftyJSON访问数据,因为它在我尝试从我的JSON数组创建数组时返回一个错误。 – Jake

+0

这是SwiftyJSON的替代方案,您应该使用它而不是 –

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) 

我认为这是有帮助的。

+0

您可以添加要解析的JSON吗? – Jake

+0

http://api.openweathermap.org/data/2.5/forecast?q=beograd&appid=7c0f97effa6938625b48aecf94e4501c这是链接并粘贴到jsonLint中,您可以看到json的外观如何。 –