Codable and JSON data
Codable and JSON data
A school sends a small student record to another program. JSON is a text data format with named fields, arrays and primitive values. Codable combines Swift’s encoding and decoding capabilities so suitable types can move between Swift values and supported data representations.
What you’ll learn
- Decode a typed record and round-trip it through JSON.
- Separate structural decoding from score-range validation.
Codable and JSON data in the example
JSON bytes
A school sends a small student record to another program.
JSON bytesDecode typed record
JSONEncoder produces Data containing JSON bytes; JSONDecoder reads those bytes into a requested type.
Decode typed recordEncode and decode again
Decoding creates a typed student from the known JSON fields.
Encode and decode again
How codable and json data works
JSONEncoder produces Data containing JSON bytes; JSONDecoder reads those bytes into a requested type. Synthesized conformance uses property names unless you define CodingKeys or custom behaviour. A successful decode checks structural requirements but does not automatically validate a school’s score policy.
Work through codable and json data
Save this complete program as main.swift and run it with the Swift toolchain. No separate input file is needed.
Swift · complete program
import Foundation
struct Student: Codable { let name: String; let score: Int }
let data = Data(#"{"name":"Diya","score":80}"#.utf8)
do {
let student = try JSONDecoder().decode(Student.self, from: data)
print(student.name, student.score)
let encoded = try JSONEncoder().encode(student)
let restored = try JSONDecoder().decode(Student.self, from: encoded)
print(restored.score)
} catch { print("Invalid student JSON") }Expected output
Diya 80
80Follow the execution
Decoding creates a typed student from the known JSON fields. Encoding and decoding again preserves the score. We print the typed values rather than claiming JSON object keys always appear in one display order.
Try this program in the Swift compiler. Paste the complete source above.
Practice: Codable and JSON data
Your task: Would a JSON score of 120 necessarily fail this decode?
Swift · complete program
import Foundation
struct Student: Codable { let name: String; let score: Int }
let data = Data(#"{"name":"Diya","score":80}"#.utf8)
do {
let student = try JSONDecoder().decode(Student.self, from: data)
print(student.name, student.score)
let encoded = try JSONEncoder().encode(student)
let restored = try JSONDecoder().decode(Student.self, from: encoded)
print(restored.score)
} catch { print("Invalid student JSON") }Worked answer
No. It is an Int and fits the synthesized structure. Add domain validation or custom decoding if the contract requires 0...100.
Validate meaning after decoding
Unknown fields are ordinarily ignored by synthesized decoding, while required missing fields and incompatible types can fail. Define date strategies, optional fields and versioning intentionally. Never treat successful parsing as proof of trusted or appropriate data.
Check your decision
Validate meaning after decoding
No. It is an Int and fits the synthesized structure. Add domain validation or custom decoding if the contract requires 0...100. Unknown fields are ordinarily ignored by synthesized decoding, while required missing fields and incompatible types can fail.
Further reading: official Swift language guide.
Reaching the recap and completing the quizzes are separate milestones.