Benjamin RD
Benjamin RD

Reputation: 12034

Swift - Convert [[String:Any?]] to Data

I have an [[String:Any]] object populated like:

var result : [[String : Any]] = [[String : Any]]()

And I need convert it to Data.

I'm just using: JSONEncoder().encode(result) To convert it.

But I get this error:

Generic parameter 'T' could not be inferred

Exist a simple way to convert a [[String:Any?]] object toData` ?

Upvotes: 20

Views: 21674

Answers (2)

Saurabh Sharma
Saurabh Sharma

Reputation: 1958

You can also using struct for that and using

let data = try? JSONEncoder().encode(struct_Object))

Upvotes: -1

David Pasztor
David Pasztor

Reputation: 54706

JSONEncoder can only encode objects whose type conforms to Encodable. If you want to encode Any to JSON, you need to use JSONSerialization to do that.

let jsonData = try? JSONSerialization.data(withJSONObject:result)

Upvotes: 45

Related Questions