美文网首页
5.使用JSONSerialization,JSON数据与对象相

5.使用JSONSerialization,JSON数据与对象相

作者: noonez | 来源:发表于2016-03-25 15:02 被阅读129次

对JSON数据与本地对象相互转化进行封装

import Foundation

class JSONSerialization: NSObject {
    static func toJSONWithObject(data:NSDictionary)->NSData?{
        var result:NSData?
        if NSJSONSerialization.isValidJSONObject(data) {
            do{
                result = try NSJSONSerialization.dataWithJSONObject(data, options: [])
            }catch {
                print("JSON化失败.")
            }
        }
        return result
    }
    static func toJSONWithArry(arr:NSArray)->NSData?{
        var result:NSData?
        if NSJSONSerialization.isValidJSONObject(arr) {
            do{
                result = try NSJSONSerialization.dataWithJSONObject(arr, options:[])
            }catch {
                print("JSON化失败.")
            }
        }
        return result
    }
    
    static func toJSONWith(data:DataAndType)->NSData?{
        var result:NSData?
        switch data.type{
        case .Array:
            result = toJSONWithArry(data.arr!)
        case .Dictionary:
            result = toJSONWithObject(data.object!)
        }
        return result
    }
    
    static func toObjectWithJSON(json:NSData)->NSDictionary?{
        var object:NSDictionary?
        do{
            try object = NSJSONSerialization.JSONObjectWithData(json, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
        }catch{
            print("JSON转Object失败.")
        }
        return object
    }
    static func toArrayWithJSON(json:NSData)->NSArray?{
        var arr:NSArray?
        do{
            try arr = NSJSONSerialization.JSONObjectWithData(json, options: NSJSONReadingOptions.AllowFragments) as? NSArray
        }catch{
            print("JSON转Object失败.")
        }
        return arr
    }
    static func toDataWithJSON(json:NSData)->DataAndType?{
        if let object = toObjectWithJSON(json){
            return DataAndType(object: object)
        }
        if let arr = toArrayWithJSON(json){
            return DataAndType(arr: arr)
        }
        return nil
    }
}

相关文章

网友评论

      本文标题:5.使用JSONSerialization,JSON数据与对象相

      本文链接:https://www.haomeiwen.com/subject/nbfdlttx.html