Search code examples
iosswiftsocketstcpsocket.io

How do I parse [String : Any]() (Swift Dictionary) to TCP/IP Server?


How to parse [String : Any]() like

{"Name":"","Device":"","Auth":"","Version":"","ObjectID":""}

which each ending with null character(through socket TCP/IP).

I can easily send String to TCP/IP Server, but couldn't able to send dictionary.

It would be great if any one suggest any solutions!!


Solution

  • You can convert dictionaries to Data using either JSONSerialization or the Codable protocol (actually the Encodable protocol in this case). Both methods convert objects to JSON Data, which you could then send via a socket as you describe. (You might need to convert that Data to a UTF8 string and add a null terminator first.)

    However, either JSONSerialization or the Encodable protocol require that all the elements of your dictionary be types that can be encoded. If your dictionary is of type [String:Any] you can't be sure that some of the values are of a type that can't be encoded.

    You need to constrain your object model to types that can be encoded. Can you describe your data more specifically? In your example it appears that all the entries are of type [String:String], which would be trivial to convert to JSON.