json from data in swift

To convert data to JSON in Swift, you can use the JSONSerialization class. Here is an example:

main.swift
do {
    let data = try JSONSerialization.data(withJSONObject: yourData, options: [])
    let jsonString = String(data: data, encoding: .utf8)
} catch {
    print(error.localizedDescription)
}
193 chars
7 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.swift
struct Person: Codable {
    let name: String
    let age: Int
}

do {
    let person = Person(name: "John", age: 30)
    let encoder = JSONEncoder()
    let data = try encoder.encode(person)
    let jsonString = String(data: data, encoding: .utf8)
} catch {
    print(error.localizedDescription)
}
299 chars
14 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.

related categories

gistlibby LogSnag