Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 342
rocklyve Avatar asked Oct 31 '25 04:10

rocklyve


2 Answers

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]
like image 128
vadian Avatar answered Nov 03 '25 01:11

vadian


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

like image 40
Sh_Khan Avatar answered Nov 03 '25 01:11

Sh_Khan