Swift 读取,处理Json数据

        /*
        {
        "id": "001",
        "name": "xyz",
        "data": ["100", "220", "300", "400"]
        }
        */
        
        //从一个本地项目资源中读取data.Json文件
        var path: String = NSBundle.mainBundle().pathForResource("data", ofType: "Json")!
        var nsUrl = NSURL(fileURLWithPath: path)
        var nsData: NSData = NSData(contentsOfURL: nsUrl!)!
        
        //读取Json数据
        var json: AnyObject? = NSJSONSerialization.JSONObjectWithData(nsData, options: NSJSONReadingOptions.allZeros, error:nil)

        //读取普通数据
        var id: String = json?.objectForKey("id") as String
        println(id)
        
        //读取数组类型数据
        var array: [String] = json?.objectForKey("data") as [String]
        println(array.count)

        //额外的注意事项
        if let name = json?.objectForKey("name") {
            //在使用if let语句的时候,swift会自动进行拆包
            println(name) //=> 此处显示的是zyx
        }
        
        //这个则不会自然拆包
        let name1 = json?.objectForKey("name")
        println(name1) //=> 此处显示的是Optional(zyx)

        //简单的Json =》 文本转换
        var dict = ["id":"002", "name": "abc"]
        
        var jsonDict = NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions.allZeros, error: nil)
        
        //直接写入文件
        jsonDict?.writeToFile("/正确路径/test.json", atomically: true)
        
        //也可以把Json转换为String字符串
        var str = NSString(data: jsonDict!, encoding: NSUTF8StringEncoding)



你可能感兴趣的:(Swift)