Swift 3.0: Data to JSON [String : Any]
Asked Answered
P

2

41

Evening, I'm trying to creating an APIClient, but I'm having a problem with a warning: APIClient.swift:53:81: Cast from 'Data' to unrelated type '[String : Any]' always fails

In this code I'm trying to convert Data into JSON as a dictionary [String : Any].

I guess the compiler can't know if this cast could or could not be possible so it throws the error, but I'm pretty sure it will work. So how can I avoid this warning or how can I write safer code?

case 200:
         do {
            let json = try JSONSerialization.data(withJSONObject: data!, options: []) as? [String : Any]
            completion(json, HTTPResponse, nil)
         } catch let error {
             completion(nil, HTTPResponse, error)
         }
Pournaras answered 10/9, 2016 at 15:20 Comment(1)
You're using the wrong method.Riding
P
96

The right method is:

do {  
    let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String : Any]
} catch {
    print("errorMsg")
}

Thanks to Eric Aya

Pournaras answered 10/9, 2016 at 15:26 Comment(3)
Without a "?" after the try, the compiler will likely throw an error saying "Errors thrown from here are not handled"Phox
add this line inside the do{ <this_code> }catch{ print("erroMsg") }Scratch
No exact matches in call to class method 'jsonObject'Carlson
A
1

for Swift 5.*

with this function you can decode your api data to your codable struct, its also nice to catch to decoding errors detailed.

  func decodeDataToObject<T: Codable>(data : Data?)->T?{
        
        if let dt = data{
            do{
              
               return try JSONDecoder().decode(T.self, from: dt)
            
        }  catch let DecodingError.dataCorrupted(context) {
            print(context)
        } catch let DecodingError.keyNotFound(key, context) {
            print("Key '\(key)' not found:", context.debugDescription)
            print("codingPath:", context.codingPath)
        } catch let DecodingError.valueNotFound(value, context) {
            print("Value '\(value)' not found:", context.debugDescription)
            print("codingPath:", context.codingPath)
        } catch let DecodingError.typeMismatch(type, context)  {
            print("Type '\(type)' mismatch:", context.debugDescription)
            print("codingPath:", context.codingPath)
        } catch {
            print("error: ", error)
        }
        }
        
        return nil
    }

usage; let user:User = decodeDataToObject(data: data)

Antigua answered 18/7, 2022 at 7:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.