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
You are using the wrong API, data(withJSONObject creates Data from a array or dictionary
You need the other way round. To resolve the issues remove the exclamation mark after encodedJson
json = try JSONSerialization.jsonObject(with: encodedJson) as? [String : Any]
and declare json as optional
var json: [String: Any]?
Or – if the JSON is guaranteed to be always a dictionary – force unwrap the object
json = try JSONSerialization.jsonObject(with: encodedJson) as! [String : Any]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With