將class 只有一層轉換成Dictionary後,再轉成String


extension NSObject {
    /**
     * To NSMutableDictionary then to String
     * Can override this method
     */
    public func toJsonString() -> String {
        let dictionary = NSMutableDictionary()
        let mirror = Mirror(reflecting: self)
        for (label, value) in mirror.children
        {
            let value = Utilities.unwrap(value) as? AnyObject
            dictionary.setValue(value, forKey: label!)
        }
        var jsonString: String = ""
        do {
            let data = try NSJSONSerialization.dataWithJSONObject(dictionary, options: NSJSONWritingOptions())
            jsonString = String(data: data, encoding: NSUTF8StringEncoding) ?? ""
        }
        catch let errorType
        {
            print("toJsonString: \(errorType)")
        }
        return jsonString
    }

}


========================================


將Mirror 的value取得內容值

public class Utilities
{
    public static func unwrap(subject: Any) ->
 Any? {
        var value: Any?
        let mirrored = Mirror(reflecting:subject)
        if mirrored.displayStyle != .Optional {
            value = subject
        } else if let firstChild = mirrored.children.first {
            value = firstChild.value
        }
        return value
    }
}

如果是複雜的Model,toJsonString 需要再改寫

參考資料:http://stackoverflow.com/questions/31773928/how-to...

arrow
arrow
    全站熱搜

    小賢 發表在 痞客邦 留言(0) 人氣()