swift3.0json数据解析

最近在学习swift,也是按照别人的代码敲打的水平,虽然时间不长,但是还是深刻的感觉到swift结构体和枚举的强大,下面是本人从别人代码里看到的一段关于json解析的封装,感觉非常不错所以想和大家分享分享,也借此来记录我学习的脚步。
在没有看到这段代码之前,我是用一个简单的方法进行解析,数据返回的形式是Any,我是强制性转化为AnyObject返回给调用者

let object: Any = try JSONSerialization.jsonObject(with: data, options: opt)

没有对数据类型进行任何判断,因为一般数据解析,我们都是可以提前看到数据类型的,也没有必要在这进行太多的判断,我是这样侥幸的想的。

偶尔看到了这段代码,所以也想和大家分享一下

1.定义了一个枚举类表示数据类型

public enum Type :Int{
    case number
    case string
    case bool
    case array
    case dictionary
    case null
    case unknown
}

2.然后定义了一个JSON结构体来做这件事


public struct JSON {

    
    public init(data:Data, options opt: JSONSerialization.ReadingOptions = .allowFragments, error: NSErrorPointer? = nil) {
        do {
            let object: Any = try JSONSerialization.jsonObject(with: data, options: opt)
            self.init(object as AnyObject)
            
        } catch let aError as NSError {
            if error != nil {
                error??.pointee = aError
            }
            self.init(NSNull())
        }
    }
    
    public init(_ object: AnyObject) {
        self.object = object
    }

    
    
    /// Private object
    fileprivate var rawArray: [AnyObject] = []
    fileprivate var rawDictionary: [String : AnyObject] = [:]
    fileprivate var rawString: String = ""
    fileprivate var rawNumber: NSNumber = 0
    fileprivate var rawNull: NSNull = NSNull()
    fileprivate var _type: Type = .null
    fileprivate var _error: NSError? = nil
    
    var object : AnyObject{
   
        get
        {
            switch self._type {
            case .array:
                return self.rawArray as AnyObject
            case .dictionary:
                return self.rawDictionary as AnyObject
            case .string:
                return self.rawString as AnyObject
            case .number:
                return self.rawNumber as AnyObject
            case .bool:
                return self.rawNumber as AnyObject
            default:
                return self.rawNull
            }
            
        }set{
            _error = nil
            switch newValue {
                
            case let number as NSNumber:
                if number.boolValue {
                    
                    _type = .bool
                }else{
                    _type = .number
                }
                self.rawNumber = number
                
            case let string as String:
                _type = .string
                self.rawString = string
            case  _ as NSNull:
                _type = .null
            case let array as [AnyObject]:
                _type = .array
                self.rawArray = array
            case let dictionary as [String : AnyObject]:
               
                _type = .dictionary
                self.rawDictionary = dictionary
            default:
                _type = .unknown
                _error = NSError.init(domain: "SwiftyJSONErrorDomain", code: 999, userInfo: [NSLocalizedDescriptionKey: "It is a unsupported type"])
            }
            
        }
    
    }


}

整段代码对数据类型判断的很全面,虽然代码量有点多,但是找不到方法去拒绝。

推荐阅读更多精彩内容