Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@andelf
Last active August 29, 2015 14:03
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andelf/9f687cd583dfaf674a4c to your computer and use it in GitHub Desktop.
Save andelf/9f687cd583dfaf674a4c to your computer and use it in GitHub Desktop.
Swift JSON Helper
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")
@andelf
Copy link
Author

andelf commented Jul 4, 2014

      let url = NSURL.URLWithString("http://www.weather.com.cn/data/sk/101010100.html")
        var session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
        let task = session.dataTaskWithHTTPGetRequest(url) {
            (raw, resp, err) in
            NSLog("data get ok!")
            let obj = EasyJSON(raw)
            let segs = [
                obj["weatherinfo"]["city"] as String,
                obj["weatherinfo"]["temp"] as String + "",
                obj["weatherinfo"]["WD"] as String,
                obj["weatherinfo"]["WS"] as String,
                "湿度",
                obj["weatherinfo"]["SD"] as String,
                obj["weatherinfo"]["time"] as String]

            let weatherDescription = segs.reduce("实时:", { $0 + " " + $1 })

@lingoer
Copy link

lingoer commented Jul 4, 2014

Cool!
Nice __conversion idea

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment