读取json文件内容

json文件内容:

{

    "stations": [

                 {

                 "sta_name": "北京北",

                 "sta_ename": "beijingbei",

                 "sta_code": "VAP",

                 "text": "自三峡七百里中,两岸连山,略无阙处。"

                 }]

}

Model代码:

class TrainStation:NSObject{
    static var _id:UInt = 0
    var selfId:UInt!
    var name:String!
    var ename:String!
    var code:String!
    var text:String!
    
    init(dic:NSDictionary) {
        super.init()
        

        
        self.selfId = TrainStation.id;
        self.name = dic["sta_name"] as? String
        self.ename = dic["sta_ename"] as? String
        self.code = dic["sta_code"] as? String
        self.text = dic["sta_text"] as? String
    }
    
    static var id:UInt{
        get{
            return ++_id
        }
    }
    
    
}

解析json并且实例化为model:

func getStations(){
        
        let path:String = NSBundle.mainBundle().pathForResource("stations", ofType: "json")!
        let nsData:NSData! = NSData(contentsOfURL: NSURL(fileURLWithPath: path))
        let json:AnyObject! = try? NSJSONSerialization.JSONObjectWithData(nsData, options: NSJSONReadingOptions.AllowFragments)
        let resultArr:AnyObject = json.objectForKey("stations")!
        for var dict in resultArr as! [[String: AnyObject]]
        {
            let entity = TrainStation(dic: dict)
            self.dataArr.append(entity)
            print("station\(entity.selfId):\(entity.name)")
        }
        
        
    }

  

posted @ 2016-01-22 15:15  mogul  阅读(1368)  评论(0编辑  收藏  举报