iOS 开发进阶Swift 高级进阶

Swift 数据转换

2019-03-08  本文已影响0人  屈涯
import UIKit
struct JSONUtils {

    // MARK: - JSONStringを辞書に変換する
    // - Returns: dictionary
   static func stringToDictionary(jsonString: String) -> [String: Any]? {
        let jsonData:Data = jsonString.data(using: .utf8)!
        guard let dict = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) as? [String: Any] else {
            return nil
        }
        return dict
    }

    // MARK: - 文字列への配列  文字列への辞書
    // - Returns: String
   static func objectToJSONString(object: Any) -> String? {
        if !JSONSerialization.isValidJSONObject(object) {
            return nil
        }
        if let newData : Data = try? JSONSerialization.data(withJSONObject: object, options: []) {
            guard let JSONString = String.init(data: newData, encoding: .utf8)?.replacingOccurrences(of: "\\/", with: "/") else {
                return ""
            }
            return JSONString
        }
        return nil
    }
}

extension Decodable {

    // MARK: - モデル化する辞書
    /// - Parameter keyAndValues: dicitionary
    /// - Returns: model
    static func dictionaryToModel(with keyAndValues: [String: Any]) -> Self? {
        return keyAndValues.to(self)
    }

    // MARK: - Json文字列変換モデル
    /// - Parameter JSONString: jsonString
    /// - Returns: model
    static func stringToModel(with JSONString: String) -> Self? {
        return JSONString.to(self)
    }

    // MARK: - モデル化するJsonバイナリデータ(Data)
    /// - Parameter JSONData: jsonData
    /// - Returns: model
    static func dataToModel(with JSONData: Data) -> Self? {
        return JSONData.to(self)
    }
}

extension Encodable {

    // MARK: - モデルオブジェクトからjson文字列へ
    // - Returns: jsonString
    func modelToJSON() -> String {
        do {
            let data = try? JSONEncoder().encode(self)
            guard let jsonData = data else { return "" }
            let jsonString = String(data: jsonData, encoding: .utf8)
            return jsonString ?? ""
        }
    }

    // MARK: - モデル翻訳辞書
    /// - Returns:dictionary
    func modeltoDictionary() -> [String: Any]? {
        do {
            let data = try? JSONEncoder().encode(self)
            guard let jsonData = data else { return nil }
            let jsonDic = (try? JSONSerialization.jsonObject(with: jsonData, options: [])) as? [String: Any]
            return jsonDic
        }
    }
}

extension Data {
    func to<T: Decodable>(_ modelType: T.Type) -> T? {
        if !self.isValidJSONData() {
            return nil
        }
        do {
            let modelObj = try? JSONDecoder().decode(modelType, from: self)
            return modelObj
        }
    }

    func isValidJSONData() -> Bool {
        do {
            let jsonObj = try? JSONSerialization.jsonObject(with: self, options: [])
            if jsonObj == nil {
                return false
            }
            return true
        }
    }
}

extension String {
    func to<T: Decodable>(_ modelType: T.Type) -> T? {
        do {
            if !self.isValidJSONString() {
                return nil
            }
            let data = self.data(using: .utf8)
            guard let jsonData = data else { return nil }
            let modelObj = try? JSONDecoder().decode(modelType, from: jsonData)
            return modelObj
        }
    }

    func isValidJSONString() -> Bool {
        do {
            let data = self.data(using: .utf8)
            guard let jsonData = data else { return false }
            let jsonObj = try? JSONSerialization.jsonObject(with: jsonData, options: [])
            if jsonObj == nil {
                return false
            }
            return true
        }
    }
}

extension Dictionary {
    func to<T: Decodable>(_ modelType: T.Type) -> T? {
        do {
            let data = try? JSONSerialization.data(withJSONObject: self, options: [])
            guard let jsonData = data else { return nil }
            let modelObj = try? JSONDecoder().decode(modelType, from: jsonData)
            return modelObj
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读