Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

swift

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` ?

like image 958
Benjamin RD Avatar asked Jun 12 '18 15:06

Benjamin RD


People also ask

How do you turn a string into data?

Any built-in data type can be converted into its string representation by the str() function. Built-in data type in python include:- int , float , complex , list , tuple , dict etc. Method 2 : Defining __str__() function for a user defined class to be converted to string representation.

How to convert a string into integer in Swift?

Using Int initializer Swift provides the function of integer initializers using which we can convert a string into an Int type. To handle non-numeric strings, we can use nil coalescing using which the integer initializer returns an optional integer.

How do I create a JSON file in Swift?

Drop in the Project Navigator or use XCode File->Add file to add the . json to your project. From that point on, you can edit that file directly.

What is data in Swift?

It is a collection of bytes ( [UInt8] array of unsigned integer 8 bits 0-255).


1 Answers

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)
like image 96
Dávid Pásztor Avatar answered Sep 27 '22 19:09

Dávid Pásztor