Search code examples
iosswiftdictionarymoyajson-serialization

Swift Mapping Data to [String: Any]


I would like to convert a Data type to [String: Any], but the JSONSerialization tells me:

Cannot force unwrap value of non-optional type 'Data'

var json: [String: Any]
            do{
                let jsonEncoder = JSONEncoder()
                let encodedJson = try jsonEncoder.encode(message)
                json = try JSONSerialization.data(withJSONObject: encodedJson!, options: []) as? [String : Any]
            } catch {
                log.error(error.localizedDescription)
            }
return .requestParameters(parameters: json, encoding: JSONEncoding.default)

If I remove the '!' from encodedJson, then the Message occure:

Value of optional type '[String : Any]?' not unwrapped; did you mean to use '!' or '?'?

If I remove the '?' from any?, then I use json without initializing it, of course

Didn't know how to fix this (new swift coder)

Hope this is not a stupid question


Solution

  • There is no need for this as you already have the data in encodedJson

    json = try JSONSerialization.data(withJSONObject: encodedJson!, options: []) as? [String : Any]
    

    as withJSONObject expects an object not Data , also casting it to [String:Any] will fail