Swift Json解析基础

func JSONToData(obj:Any) -> Data {
       
        //先判断是否可以转换
        if !JSONSerialization.isValidJSONObject(obj) {
            return Data.init()
        }
        
        //开始转换
        //JSONSerialization.WritingOptions.prettyPrinted 是输出JSON时的格式更容易查看。
        return try! JSONSerialization.data(withJSONObject: obj, options: .prettyPrinted)      
    }
    
    func DataToJSON(anyData:Data) -> Any {
        if JSONSerialization.isValidJSONObject(anyData) {
            return anyData
        }
        
        //开始转换
        return try! JSONSerialization.jsonObject(with: anyData, options: JSONSerialization.ReadingOptions.mutableContainers)
    }

    func jsonToStream(obj:Any,stream:OutputStream) -> (Int,NSError?) {
        //判断是否可以写入
        var error:NSError?
        if !JSONSerialization.isValidJSONObject(obj){
            return (0,error)
        }
        
        let result = JSONSerialization.writeJSONObject(obj, to: stream, options: .prettyPrinted, error: &error)
        if (error != nil) {
            return (0,error!)
        }
        return (result,nil)
    }
    
    func StreamToJSON(stream:InputStream) -> Any {
        return try! JSONSerialization.jsonObject(with: stream, options: .mutableContainers)
    }

 

Call Fuction

// 数组转换
    let  ArrayFunc = ["aa","bb","ccc"]
    // 转换
    let ArrayJsonData = JSONToData(obj: ArrayFunc)
    // 解码
    let ArrayUJson = DataToJSON(anyData: ArrayJsonData)
    // 输出
    print(ArrayUJson)

/*
打印

(
    aa,
    bb,
    ccc
)

*/
    
    //字典转换
    let dict:[String : Any]=["name":"jack","age":18]
    let dataDict=JSONToData(obj: dict)
    let dict2=DataToJSON(anyData: dataDict)
    print(dict2)

/*
打印

{
    age = 18;
    name = jack;
}

*/

 

posted on 2019-07-17 17:33  二狗你变了  阅读(824)  评论(0编辑  收藏  举报

导航