0Pricing
Swift Academy · Lesson

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

  1. Conforming to Codable
  2. Encoding with JSONEncoder
  3. Decoding with JSONDecoder
  4. Handling Optional and Nested Types
← Back to Swift Academy