How to use the JSON to Swift
- Paste a sample JSON response.
- Set the root struct name.
- Check optionals: any value that can be null or missing must be declared with ?.
- Copy the code into your Xcode project and decode with JSONDecoder.
Worked example
A snake_case user payload
Input
{"user_id":12,"display_name":"Ada","verified":true,"avatar_url":"https://example.com/a.png"}Swift
import Foundation
struct Root: Codable {
let user_id: Int
let display_name: String
let verified: Bool
let avatar_url: String
}With the default naming (keep), properties use the JSON keys as-is, so no CodingKeys are needed. Choose camelCase in the options to get displayName/avatarUrl with a generated CodingKeys enum, and change avatarUrl to URL if you want Foundation to parse it.
CodingKeys or keyDecodingStrategy?
| Approach | Pros | Cons |
|---|---|---|
| CodingKeys enum (generated) | Explicit; works with any key spelling | More code to maintain |
| decoder.keyDecodingStrategy = .convertFromSnakeCase | No CodingKeys needed for snake_case | avatar_url maps to avatarUrl, not avatarURL |
| Rename properties to match keys | Zero configuration | Non-Swifty names like user_id |
Optionals and DecodingError
A non-optional property whose key is missing throws DecodingError.keyNotFound; one that is null throws valueNotFound. Declaring the property optional (String?) makes both cases decode to nil. When the error is thrown, its codingPath tells you exactly which key failed.
Dates and numbers
Dates arrive as strings or numbers. Set decoder.dateDecodingStrategy = .iso8601 for ISO 8601 strings without fractional seconds, or use a custom formatter otherwise. Swift Int is 64-bit on all current Apple devices, so large integer IDs are safe; decimals map to Double, or Decimal for money.
JSON to Swift FAQ
How do I decode JSON in Swift?
Make the type conform to Codable (or Decodable) and call try JSONDecoder().decode(Root.self, from: data). For an array at the root, decode [Root].self.
What does keyNotFound mean in Swift JSON decoding?
A non-optional property has no matching key in the JSON. Make it optional, give the key a different raw value in CodingKeys, or check that the payload is what you expect.
Do I need CodingKeys in Swift?
Only when property names differ from the JSON keys and you are not using a key decoding strategy. If every name matches, Codable synthesizes the keys for you.
Should I use struct or class for Codable models?
Structs are the usual choice: value semantics, synthesized memberwise initializers and no reference sharing. Use a class only when you need identity or inheritance.
How do I decode ISO 8601 dates in Swift?
Set decoder.dateDecodingStrategy = .iso8601 and declare the property as Date. Fractional seconds need a custom ISO8601DateFormatter with .withFractionalSeconds.

