SwiftyJSON:无法从JSON读取数组值

时间:2016-09-01 01:56:22

标签: ios swift alamofire swifty-json

我无法使用SwiftyJSON从我的JSON获取我的字符串数组。我有这样的json

{
    "categories": {
        "202": "Women's Clothing",
        "104": "Men's Clothing"
    },
    "products": [{
        "price": 528500.0,
        "title": "Some title with long name",
        "id": "13864671"
    }..., ..., ...],
    "keywords": ["hoodie", "hoodie paramore i", "hoodie daft punk", "hoodie muse", "hoodie nirvana"]
}

我的问题是,我可以打印类别和产品,但我不能打印关键字。它只给我空白数组[]。那么这里有什么不对?

Alamofire.request(request).responseJSON {
    response in
    if response.result.error == nil {
        let json = JSON(response.result.value!)
        print(json)
        success(json)
    }else{
        error("\(response.result.error?.localizedDescription)")
    }
}

当我打印json时,我的categoriesproducts除了keywords之外没有任何价值[]

这是我在Xcode上的登录

{
  "categories" : {
    "111" : "Men's Clothing",
    "122" : "Women's Clothing"
  },
  "keywords" : [

  ],
  "products" : [
    {
      "price" : 123,
      "title" : "Long name product",
      "id" : "123123"
    }
  ]
}

任何帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:0)

试试这段代码:

  

Product.swift

import Foundation
import SwiftyJSON

class Product {

var price: Double?
var title: String?
var id: String?


init (json: JSON) {

    if let price = json["price"].double {
        self.price = price
    }

    if let title = json["title"].string {
        self.title = title
    }

    if let id = json["id"].string {
        self.id = id
    }
}

var description: String {
    get {
        var _description = ""

        if let price = self.price {
            _description += "price: \(price)\n"
        }

        if let title = self.title {
            _description += "title: \(title)\n"
        }

        if let id = self.id {
            _description += "id: \(id)\n"
        }

        return _description
    }
}
}
  

ViewController.swift

import UIKit
import SwiftyJSON

class ViewController: UIViewController {

var keywords = [String]()
var categories = [String:String]()
var products = [Product]()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    if let path = NSBundle.mainBundle().pathForResource("data", ofType: "json") {
        if let data = NSData(contentsOfFile: path) {
            let json = JSON(data: data)
            //NSLog("\(json)")

            if let keywords = json["keywords"].array {
                for keyword in keywords {
                    if let keyword = keyword.string {
                        self.keywords.append(keyword)
                    }
                }
            }

            if let categories = json["categories"].dictionary {
                for key in categories.keys {
                    if let category = categories[key]?.stringValue {
                        self.categories.updateValue(category, forKey: key)
                    }
                }
            }

            if let products = json["products"].array {
                for product in products {
                    self.products.append(Product(json: product))
                }
            }

        }
    }

    print("keywords: \(keywords)")
    print("categories: \(categories)")
    print("products:\n")
    for product in products {
        print(product.description)
    }
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
}
  

data.json

{
"categories": {
    "202": "Women's Clothing",
    "104": "Men's Clothing"
},
"products": [{
             "price": 528500.0,
             "title": "Some title with long name",
             "id": "13864671"
             },
             {
             "price": 528531200.0,
             "title": "!!Some title with long name",
             "id": "13223864671"
             }],
"keywords": ["hoodie", "hoodie paramore i", "hoodie daft punk", "hoodie muse", "hoodie nirvana"]
}

<强>结果

enter image description here