decode Json string to class object Swift

前端 未结 2 351
有刺的猬
有刺的猬 2021-01-18 17:09
 private func createWeatherObjectWith(json: Data, x:Any.Type ,completion: @escaping (_ data: Any?, _ error: Error?) -> Void) {
        do {
            let decode         


        
2条回答
  •  说谎
    说谎 (楼主)
    2021-01-18 17:37

    If you are trying to decode any type of object then use these technique

    1. Generics function

    private func createWeatherObjectWith(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. Extend Decodable

    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
            }
        }
    }
    

    Use:

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

提交回复
热议问题