swift 3.0 字典与JSON互转

2017-02-23  本文已影响0人  李大围
class JsonToSturt: NSObject {

class func dictionaryWithJsonString(jsonString:String) ->NSDictionary {
    var dicx:NSDictionary!
    let data : Data! = jsonString.data(using: .utf8)
    let dic : Any! = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)
    if dic != nil {
        dicx = dic as! NSDictionary
    }
    
    return dicx
}
class func toJSONS(representation:Any) -> String? {
    
    
    guard JSONSerialization.isValidJSONObject(representation) else {
        return nil
    }
    
    do {
        let data = try JSONSerialization.data(withJSONObject: representation, options: [])
        return String(data: data, encoding: .utf8)
    } catch {
        return nil
    }
}
上一篇下一篇

猜你喜欢

热点阅读