欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

swift-json解析数据类型

程序员文章站 2024-01-31 08:26:52
...
 let dic = NSMutableDictionary()
        dic["age"] = 20
        dic["name"] = "明月"
        dic["address"] = nil
        dic["weight"] = 1
        dic["student"] = true
        dic["list"] = ""
        
        //let array = dic["list"] as! NSArray 强行拆包会崩溃

        let list = dic["list"]
        
        if let array = list as? NSArray{//
            if array.count != 0{
               MyPrint(message: "list数组,不为空")
            }else{
               MyPrint(message: "list是空数组!")
            }
           
        }else{
            MyPrint(message: "list不是数组!")
        }
        
        let age = self.stringFromObject(object: dic["age"] as AnyObject)
//dic[AnyHashable("age")] as! String 强行拆包会崩溃
        MyPrint(message: age)
        
        let name = dic[AnyHashable("name")] as! String
        MyPrint(message: name)
        
        let weight = self.stringFromObject(object: dic["weight"] as AnyObject)
        MyPrint(message: weight)
        
        let address = self.stringFromObject(object: dic["address"] as AnyObject)
        MyPrint(message: address)
        
        let address1 = dic["address"] as? String
        MyPrint(message: address1)
        
        let student = self.stringFromObject(object: dic["student"] as AnyObject)
        
        MyPrint(message: student)
        
        var isStudent = false
        
        if student == "1" {
            isStudent = true
        }
        MyPrint(message:isStudent)
       
    }
    //Int返回值为"\(value)"、bool返回值为"0","1"
    func stringFromObject(object:AnyObject) -> String{
        var value = ""
        if let code = object as? Int{
            value = "\(code)"
        }else if let code = object as? CGFloat{
            value = "\(code)"
        }else if object is NSNull{
            value = ""
        }
        return value
    }
    
    override func viewDidAppear(_ animated: Bool) {

    }
    func arrayFromObject(object:AnyObject) -> NSArray{
        let arr = NSArray()
        //如果是类型是数组则返回数组,否则返回空数组
        if let dataArr = object as? NSArray{
            return dataArr
        }else{
            return arr
        }
    }
    

 

相关标签: json解析数据类型