3

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

rocklyve
  • 133
  • 1
  • 10

2 Answers2

4

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]
vadian
  • 274,689
  • 30
  • 353
  • 361
1

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

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87