ios-swift
/

JSON in Swift – Data Parsing with Codable

Last Sync: Today

On this page

5
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

ios-swift

JSON in Swift – Data Parsing with Codable

The Codable Protocol

In modern Swift, we use the Codable protocol (a typealias for Encodable & Decodable) to handle JSON. It allows you to convert between your native Swift types and a JSON representation without writing manual parsing logic. As an Architect, you should prioritize Structs for your JSON models to leverage value semantics and thread safety.

  1. Decoding JSON to Structs

To turn a JSON payload into a Swift object, you use the JSONDecoder. If your Python API returns snake_case keys, you can configure the decoder to automatically convert them to Swift's standard camelCase.

SWIFTRead-only
1
struct Project: Codable {
    let id: String
    let projectName: String
    let widgetCount: Int
}

let jsonData = """
{
    "id": "revo_01",
    "project_name": "AI Builder",
    "widget_count": 42
}
""".data(using: .utf8)!

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase

try {
    let project = try decoder.decode(Project.self, from: jsonData)
    print("Parsed: \(project.projectName)")
} catch {
    print("Decoding Error: \(error)")
}

  1. Handling Custom Keys with CodingKeys

When an API uses keys that are reserved words in Swift or don't match your naming conventions, you use the CodingKeys enum. This acts as a mapping layer between the JSON key and your property name.

SWIFTRead-only
1
struct User: Codable {
    let name: String
    let emailAddress: String

    enum CodingKeys: String, CodingKey {
        case name
        case emailAddress = "user_primary_email"
    }
}

  1. Encodable: Sending Data Back

Encoding is the reverse process. You use JSONEncoder to turn your Swift objects back into JSON Data, which can then be sent to your backend or passed through a Method Channel to Flutter.

JSON Management Comparison

FeatureSwift (Codable)Dart (Flutter)
Code GenNot required (Built into compiler)Required (build_runner / json_serializable)
MappingCodingKeys enumAnnotations (@JsonKey)
Null SafetyVia Optionals (?)Via Null-safe types
PerformanceHigh (Native binary)High (AOT Compiled)
Snake CasekeyDecodingStrategyManual or generator config

Test Your Knowledge

Q1
of 3

Which protocol must a Swift Struct adopt to support both JSON encoding and decoding?

A
Jsonable
B
Codable
C
Convertible
D
Encodable
Q2
of 3

Which object is responsible for converting JSON Data into a native Swift Struct instance?

A
JSONEncoder
B
JSONDecoder
C
CodableParser
D
UrlSession
Q3
of 3

What is the purpose of the 'CodingKeys' enumeration inside a Struct?

A
To encrypt the JSON data
B
To map JSON keys to custom property names
C
To define the order of variables in memory
D
To bypass security checks

Frequently Asked Questions

How do I handle nested JSON objects?

If your JSON has nested objects, simply define child Structs that also conform to 'Codable'. Swift will automatically recursively decode the entire tree into your model.

What happens if a key is missing in the JSON?

If a key is missing and the corresponding property in your Struct is not an 'Optional' (marked with ?), the decoder will throw a 'keyNotFound' error. Always use Optionals for keys that are not guaranteed to exist.

Can I parse an array of JSON objects?

Yes. You simply decode as an array of your type: 'try decoder.decode([Project].self, from: data)'. This is much cleaner than the manual mapping often seen in older Swift code.

Previous

ios networking

Next

ios coredata

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.