To convert data to JSON in Swift, you can use the JSONSerialization
class. Here is an example:
main.swift193 chars7 lines
In the above code, replace yourData
with the data that you want to convert to JSON.
Another way is to use Codable, which is a protocol that allows you to encode and decode custom types to and from JSON. Here's an example:
main.swift299 chars14 lines
In this code, the Person
struct conforms to the Codable
protocol, which means it can be encoded to JSON using the JSONEncoder
class. Replace person
with your own custom object that conforms to Codable
.
gistlibby LogSnag