SwiftyJSON в 60 строк

xcode
swift

#1
import Foundation

class JSON {
    
    var int: Int? {
        return _object as? Int
    }
    var float: Float? {
        return _object as? Float
    }
    var bool: Bool? {
        return _object as? Bool
    }
    var string: String? {
        return _object as? String
    }
    var dictionary: NSDictionary? {
        return _object as? NSDictionary
    }
    var array: NSArray? {
        return _object as? NSArray
    }
    var object: AnyObject? {
        return _object as? AnyObject
    }
    
    private var _object: NSObject?
    
    init(_ object: NSObject?) {
        _object = object
    }
    
    subscript(key: String) -> JSON? {
        if let dictionary = _object as? NSDictionary {
            return JSON(dictionary[key] as? NSObject)
        } else {
            return nil
        }
    }
    subscript(index: Int) -> JSON? {
        if let array = _object as? NSArray {
            return JSON(array[index] as? NSObject)
        } else {
            return nil
        }
    }
}

extension JSON {
    convenience init?(data: NSData) {
        if let object = try? NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) {
            self.init(object as? NSObject)
        } else {
            return nil
        }
    }
}

Пример использования:

let data = "[{\"object\":{\"array\":[{\"string\":\"Test\"}]}}]".dataUsingEncoding(NSUTF8StringEncoding)!
let json = JSON(data: data)
        
if let str = json?[0]?["object"]?["array"]?[0]?["string"]?.string {
    print(str)
}

Скачать