How to Parse JSON in Swift
Swift uses the Codable protocol with JSONDecoder and JSONEncoder from Foundation. Conform your struct to Codable and decode from Data.
Decode into a Codable struct
Conform to Codable and decode the JSON Data into your type.
swift
struct User: Codable {
let name: String
let roles: [String]
}
let data = Data(text.utf8)
let user = try JSONDecoder().decode(User.self, from: data)
print(user.name)Map snake_case keys
Set keyDecodingStrategy to convert snake_case JSON keys to camelCase properties automatically.
swift
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let user = try decoder.decode(User.self, from: data)Encode and pretty-print
JSONEncoder serializes; set outputFormatting for pretty output.
swift
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
let out = try encoder.encode(user)
print(String(data: out, encoding: .utf8)!)