Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

decode Json string to class object Swift

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

Here I write above code to decode Json string to class object by passing class type .But it gives the following error

Cannot invoke 'decode' with an argument list of type '(Any.Type, from: Data)'
like image 897
Kasun Wickramanayake Avatar asked Nov 19 '18 02:11

Kasun Wickramanayake


People also ask

Which object can decode JSON data into native Swift types?

You can use Codable in Swift to encode and decode custom data formats, such as JSON, to native Swift objects. It's incredibly easy to map Swift objects to JSON data, and vice versa, by simply adopting the Codable protocol.


2 Answers

Trying to decode any type of Object to String in Swift 4.1

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) 
}
like image 45
Rohit Parihar Avatar answered Oct 07 '22 21:10

Rohit Parihar


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

1. Generics function

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. 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")
like image 132
prex Avatar answered Oct 07 '22 21:10

prex