Last active
August 29, 2015 14:03
-
-
Save andelf/9f687cd583dfaf674a4c to your computer and use it in GitHub Desktop.
Swift JSON Helper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
//let raw = String.stringWithContentsOfURL(NSURL(string: "http://www.weather.com.cn/data/sk/101010100.html")) | |
struct EasyJSON { | |
var _obj: AnyObject! | |
init(_ obj: AnyObject) { | |
//assert(NSJSONSerialization.isValidJSONObject(obj), "must be valid json object") | |
_obj = obj | |
} | |
init(_ data: NSData) { | |
var err: NSError? | |
_obj = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(), error: &err) | |
} | |
subscript (key: String) -> EasyJSON! { | |
if let dict = _obj as? NSDictionary { | |
return EasyJSON(dict[key]) | |
} | |
return nil | |
} | |
subscript (index: Int) -> EasyJSON! { | |
if let array = _obj as? NSArray { | |
return EasyJSON(array[index]) | |
} | |
return nil | |
} | |
var isObject: Bool { | |
return (_obj as? NSDictionary).getLogicValue() | |
} | |
var isArray: Bool { | |
return (_obj as? NSArray).getLogicValue() | |
} | |
var isNumber: Bool { | |
return (_obj as? NSNumber).getLogicValue() | |
} | |
var isString: Bool { | |
return (_obj as? String).getLogicValue() | |
} | |
var isBool: Bool { | |
return (_obj as? Bool).getLogicValue() | |
} | |
@conversion @transparent func __conversion() -> String { | |
return _obj as String | |
} | |
@conversion @transparent func __conversion() -> NSNumber { | |
return _obj as NSNumber | |
} | |
@conversion @transparent func __conversion() -> Int? { | |
if let val = _obj as? Int { | |
return val | |
} else if let val = _obj as? String { | |
return val.toInt() | |
} else { | |
return nil | |
} | |
} | |
} | |
extension EasyJSON: LogicValue { | |
@transparent func getLogicValue() -> Bool { | |
if let val = _obj as? Bool { | |
return val | |
} | |
// FIXME: logically wrong | |
return false | |
} | |
} | |
let raw = NSData(contentsOfURL: NSURL(string: "http://www.weather.com.cn/data/sk/101010100.html")) | |
var err: NSError? | |
let raw_obj = NSJSONSerialization.JSONObjectWithData(raw, options: NSJSONReadingOptions(), error: &err) | |
let obj = EasyJSON(raw_obj) | |
dump(obj, name: "json") | |
let city: String = obj["weatherinfo"]["city"] | |
dump(city) | |
let temp: Int = obj["weatherinfo"]["temp"]! | |
dump(temp, name: "temperature") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment