There are two methods for converting Swift objects to JSON format:
Swift 4 introduced a Codable protocol that provides a convenient way to decode (deserialize) and encode (serialize) data types to and from JSON. To use Codable, you need to define a struct or class that conforms to it, and then use an instance of JSONDecoder or JSONEncoder to convert between the Swift object and JSON format.
For example, to encode a custom struct to JSON format:
struct Person: Codable {
var name: String
var age: Int
}
let person = Person(name: "John", age: 30)
let encoder = JSONEncoder()
do {
let jsonData = try encoder.encode(person)
let jsonString = String(data: jsonData, encoding: .utf8)
print(jsonString)
} catch {
print(error.localizedDescription)
}
Output:
{"name":"John","age":30}
SwiftyJSON is a third-party library that provides a simple way to parse JSON data in Swift. It supports object mapping, error handling, and chaining syntax.
To use SwiftyJSON, you need to include it in your project using CocoaPods or Swift Package Manager, and then use its JSON() method to convert between the Swift object and JSON format.
For example, to encode a custom struct to JSON format:
import SwiftyJSON
struct Person {
var name: String
var age: Int
func toJSON() -> JSON {
return JSON(["name": name, "age": age])
}
}
let person = Person(name: "John", age: 30)
let jsonString = person.toJSON().rawString()
print(jsonString)
Output:
{"name":"John","age":30}
Asked: 2023-03-31 11:00:00 +0000
Seen: 12 times
Last updated: Sep 12 '22