将Json字符串解码为类对象Swift

时间:2018-11-19 02:22:06

标签: swift decode codable

 private func createWeatherObjectWith(json: Data, x:Any.Type ,completion: @escaping (_ data: Any?, _ error: Error?) -> Void) {
        do {
            let decoder = JSONDecoder()
            decoder.keyDecodingStrategy = .convertFromSnakeCase
            let weather = try decoder.decode(x.self, from: json)
            return completion(weather, nil)
        } catch let error {
            print("Error creating current weather from JSON because: \(error.localizedDescription)")
            return completion(nil, error)
        }
    }

在这里我编写了上面的代码以通过传递类类型将Json字符串解码为类对象,但这会产生以下错误

Cannot invoke 'decode' with an argument list of type '(Any.Type, from: Data)'

2 个答案:

答案 0 :(得分:5)

如果您尝试解码任何类型的对象,请使用这些技术

1。泛型函数

private func createWeatherObjectWith<T: Decodable>(json: Data, Object:T.Type ,completion: @escaping (_ data: T?, _ error: Error?) -> Void) {
    do {
        let decoder = JSONDecoder()
        decoder.keyDecodingStrategy = .convertFromSnakeCase
        let weather = try decoder.decode(T.self, from: json)
        return completion(weather, nil)
    } catch let error {
        return completion(nil, error)
    }
}

2。扩展可破坏性

extension Decodable {
    static func map(JSONString:String) -> Self? {
        do {
            let decoder = JSONDecoder()
            decoder.keyDecodingStrategy = .convertFromSnakeCase
            return try decoder.decode(Self.self, from: Data(JSONString.utf8))
        } catch let error {
            print(error)
            return nil
        }
    }
}

使用:

let user = User.map(JSONString:"your JSON string")
let users = [User].map(JSONString:"your JSON string")

答案 1 :(得分:1)

尝试在Swift 4.1中将任何类型的Object解码为String

func convertAnyObjectToJSONString(from object:Any) -> String? {

    guard let data = try? JSONSerialization.data(withJSONObject: object, options: []) else { 

        return nil 
    }

    return String(data: data, encoding: String.Encoding.utf8) 
}