Encoding with JSONEncoder
Produce JSON data from Swift values.
Creating a JSONEncoder
JSONEncoder is the workhorse that turns any Encodable value into JSON Data. Create one, then call encode(_:) on your value.
import Foundation
struct Movie: Codable {
var title: String
var year: Int
}
let encoder = JSONEncoder()
let data = try encoder.encode(Movie(title: "Up", year: 2009))
print(data.count, "bytes")From Data to a Readable String
encode(_:) returns binary Data. To read it, decode the bytes as UTF-8 with String(data:encoding:).
import Foundation
struct Movie: Codable {
var title: String
var year: Int
}
let data = try JSONEncoder().encode(Movie(title: "Up", year: 2009))
let text = String(data: data, encoding: .utf8)!
print(text)All lessons in this course
- Conforming to Codable
- Encoding with JSONEncoder
- Decoding with JSONDecoder
- Handling Optional and Nested Types