How to use NSJSONSerialization
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
NSJSONSerialization (now JSONSerialization in Swift) converts between JSON data and Foundation objects (Dictionary, Array, String, Number). It provides jsonObject(with:) to parse JSON Data into Foundation objects, and data(withJSONObject:) to serialize Foundation objects into JSON Data. While Codable (Swift 4+) is now the preferred approach for type-safe JSON handling, JSONSerialization remains useful for dynamic JSON structures, quick prototyping, and Objective-C compatibility.
Parsing JSON Data to Dictionary
jsonObject(with:) returns Any — you must cast to the expected type ([String: Any] for objects, [Any] for arrays). Every nested value also requires type casting.
Parsing a JSON Array
Serializing Dictionary to JSON Data
options: .prettyPrinted formats the output with indentation. For compact output (APIs), omit the option or pass [].
Validating JSON
isValidJSONObject() checks if the object graph contains only JSON-compatible types before attempting serialization.
Network Request Example
Codable Alternative (Preferred in Modern Swift)
Reading/Writing Options
Common Pitfalls
- Excessive type casting: Every value from
JSONSerializationisAnyand requires manualas?casting. This is verbose and error-prone for complex JSON. UseCodablefor known structures. - Non-serializable types:
Date,URL, custom objects, andDatacannot be serialized byJSONSerialization. Convert them to strings or numbers first, or useCodablewith customencodemethods. - Force unwrapping crashes:
dict["key"] as! Stringcrashes if the key is missing or the type is wrong. Always useas?with optional binding or default values. - Fragments not allowed by default: Top-level JSON values like
"hello"or42(not objects or arrays) cause errors without.fragmentsAllowed. Add this option if your API returns non-object responses. - Key ordering not guaranteed: Dictionary keys in JSON output are unordered by default. Use
.sortedKeys(iOS 11+) if you need deterministic output for testing or caching.
Summary
JSONSerialization.jsonObject(with: data)parses JSON data into Foundation objectsJSONSerialization.data(withJSONObject: obj)serializes Foundation objects to JSON data- Use
isValidJSONObject()to verify objects contain only JSON-compatible types before serializing - Every parsed value is
Any— useas?casting for type safety - Prefer
Codable(JSONDecoder/JSONEncoder) for type-safe JSON handling in modern Swift JSONSerializationremains useful for dynamic JSON and Objective-C interoperability
Related reading
- How to use NSLocalizedString function with variables in Swift?
- How to use NSURLConnection to connect with SSL for an untrusted cert?
- How to use presentModalViewController to create a transparent view
- How to use pull-to-refresh in Swift?
- How to use pull-to-refresh in Swift?
- How to use putExtra and getExtra for string data
- How to use RecyclerView inside NestedScrollView?
- How to use Runnable in Monodroid for Android
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.