在swift中使用JSON解析

时间:2015-03-22 12:49:21

标签: arrays json swift dictionary nsurlconnection

我正在尝试将JSON格式的数据从我的服务器加载到IOS应用程序中。

这是我的JSON:

[
  {
    "BankName": "bank1",
    "CurrencyName": "cur1",
    "SellRate": "0.65",
    "BuyRate": "0.55",
    "OfficialRate": "0.6"
  },
  {
    "BankName": "bank1",
    "CurrencyName": "cur2",
    "SellRate": "1.65",
    "BuyRate": "1.55",
    "OfficialRate": "1.6"
  }
]

我的项目中有2个文件:

1:

import Foundation
class Shot {
    var bankName: String!
    var currencyName: String!
    var sellRate: String!
    var buyRate: String!
    var offRate: String!

    init (data: NSDictionary) {          
        self.bankName = getStringFromJSON(data, key:"BankName")
        self.currencyName = getStringFromJSON(data, key:"CurrencyName")
        self.sellRate = getStringFromJSON(data, key:"SellRate")
        self.buyRate = getStringFromJSON(data, key:"BuyRate")
        self.offRate = getStringFromJSON(data, key: "OfficialRate")
    }

    func getStringFromJSON(data: NSDictionary, key: String) -> String {                    
        if let info = data[key] as? String{
            return info
        }
        return ""
    }
}

2:

import Foundation
class JsonTest {    
    func loadJson(completion: ((AnyObject) -> Void)!) {    
        var urlString = "http://a.com/g.php"        
        let session = NSURLSession.sharedSession()
        let sourceUrl = NSURL(string: urlString)

        var task = session.dataTaskWithURL(sourceUrl!){
            (data, response, error) -> Void in

            if error != nil {
               println(error.localizedDescription)
            } else {

                var error: NSError?
                var jsonData = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &error) as NSArray

                var shots = [Shot]()

                println(jsonData)

                for shot in jsonData{
                    let shot = Shot(data: shot as NSDictionary)
                    shots.append(shot)                    
                }                
                println(shots)   //[jsontest.Shot, jsontest.Shot]                
            }
        }        
        task.resume()
    }
}

我正在尝试在应用启动时自动填充数组。为此,我在mainViewController类中有一个代码。

override func viewDidLoad() {
    super.viewDidLoad()

   let api = JsonTest()
    api.loadJson(nil)

}

当我尝试在第二个文件中打印镜头变量时,会出现问题。 当我期待字典数组时,它会返回[jsontest.Shot, jsontest.Shot]

println(jsonData)正常工作并显示来自网址的JSON数据。

有人可以告诉我的程序有什么问题吗?

2 个答案:

答案 0 :(得分:2)

“shot”是Shot的实例数组,而不是字典:

class Shot {
    var bankName: String!
    var currencyName: String!
    var sellRate: String!
    var buyRate: String!
    var offRate: String!

    init (data: NSDictionary) {
        self.bankName = getStringFromJSON(data, key:"BankName")
        self.currencyName = getStringFromJSON(data, key:"CurrencyName")
        self.sellRate = getStringFromJSON(data, key:"SellRate")
        self.buyRate = getStringFromJSON(data, key:"BuyRate")
        self.offRate = getStringFromJSON(data, key: "OfficialRate")
    }

    func getStringFromJSON(data: NSDictionary, key: String) -> String {
        if let info = data[key] as? String{
            return info
        }
        return ""
    }
}

var shots = [Shot]()
let urlString = "http://almazini.lt/getrates.php"
let sourceUrl = NSURL(string: urlString)
// Using NSData instead of NSURLSession for experimenting in Playground
let data = NSData(contentsOfURL: sourceUrl!)
var error: NSError?
// As I'm using Swift 1.2 I had to change "as" with "as!"
let jsonData = NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers, error: &error) as! NSArray
for shot in jsonData{
    let shot = Shot(data: shot as! NSDictionary)
    shots.append(shot)
}
println(shots[0].bankName)

screenshot

更新Swift 2

var shots = [Shot]()
let urlString = "http://almazini.lt/getrates.php"
// Using NSData instead of NSURLSession for experimenting in Playground
if let sourceUrl = NSURL(string: urlString) {
    NSURLSession.sharedSession().dataTaskWithURL(sourceUrl, completionHandler: { (data, response, error) in
        if error == nil {
            if let data = data, jsonData = try? NSJSONSerialization.JSONObjectWithData(data, options: []), jsonArray = jsonData as? [NSDictionary] {
                for item in jsonArray {
                    let shot = Shot(data: item)
                    shots.append(shot)
                }
                print(shots[0].bankName)
            } else {
                print("no JSON data")
            }
        } else {
            print(error!.localizedDescription)
        }
    }).resume()
}

答案 1 :(得分:0)

似乎有两个问题:

  1. 您尝试使用println进行调试,而不是设置断点并检查对象值。
  2. 您尚未为对象创建descriptiondebugDescription属性,因此对象上的println只是使用了一些默认实现。
  3. shots是您自定义对象的数组,因此当您致电println时,它会使用description Array来打印对象在数组中,逗号分隔,并在方括号内。

    Swift中类的默认description属性只打印类名。

    理想情况下,您应该使用断点来检查对象的值,以确定它是否已正确初始化,但如果确保对它们进行正确打印非常重要,那么它只是一个问题实现description属性:

    override var description: String {
        get {
            // build and return some string that represents your Shot object
        } 
    }