JSON ยท SWIFT RECIPE

Encode a model as JSON

Serialize a model with stable, readable formatting.

main.swift
import Foundation
struct Project: Encodable { let name: String; let stars: Int }
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
do {
    let data = try encoder.encode(Project(name: "iSwift", stars: 5))
    print(String(decoding: data, as: UTF8.self))
} catch { print(error) }

How it works

JSONEncoder produces Data. Decode it as UTF-8 to display the JSON. Sorted keys help produce readable diffs; consumers should not rely on key order.

Keep in mind

Configure date and key strategies to match your API contract.

Read the Swift language reference