簡體   English   中英

SwiftyJSON:無法從JSON讀取數組值

[英]SwiftyJSON: Can't read array value from 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"
    }
  ]
}

任何幫助,將不勝感激。 謝謝!

試試這個代碼:

產品速匯

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"]
}

結果

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM