How to Convert JSON to Objective-C Classes (NSString, NSNumber, NSArray)
An Objective-C model is a plain NSObject subclass with a @property for each field, and the fiddly parts are choosing the right Foundation type for each key and mapping JSON keys like id that collide with reserved names. Generating the header from a real sample gets both right. This guide covers how the mapping works, the fastest way to do it, and the Objective-C-specific gotchas around NSNumber, property attributes, and reserved names.
The fastest route: a browser generator
For a one-off, paste the JSON into the JSON to Objective-C converter. It reads the sample, infers the Foundation type of every field, and writes an @interface per object with a @property for each key: nested objects become their own classes, arrays become typed NSArray properties, and reserved keys are renamed to safe properties. Because it runs entirely in your browser, the JSON never leaves your machine, which matters when the sample is a real production response.
If the JSON will not convert, it is almost always invalid rather than genuinely unconvertible. Run it through the JSON parser to find the exact syntax error, or format it so you can see the structure first.
How JSON maps to Objective-C
A generator makes the same decisions every time, and they follow what NSJSONSerialization actually returns.
- Objects become classes. Each object turns into an
@interfacesubclassingNSObject, with a@propertyper key. - Nested objects get their own class. Rather than inlining a deep object, the generator names it, forward-declares it with
@class, and references it from the parent. - Arrays become typed
NSArray.["a","b"]becomesNSArray<NSString *> *; an array of objects becomesNSArray<Item *> *. - Strings become
NSString, numbers and booleans becomeNSNumber.
Here is the shape of a simple conversion:
{ "name": "Ada", "age": 36 }
becomes:
#import <Foundation/Foundation.h>
@interface Root : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, strong) NSNumber *age;
@end
Why numbers are NSNumber
NSJSONSerialization, the Foundation class that parses JSON, decodes every JSON number and every boolean into an NSNumber. It does not know whether you want an int, a double, or a BOOL, so it boxes them all. That is why generated model properties use NSNumber rather than a scalar: the property matches exactly what the parser hands you. You read the value out with the accessor you need:
NSInteger qty = order.qty.integerValue;
double total = order.total.doubleValue;
BOOL vip = order.customer.vip.boolValue;
Using a scalar property like NSInteger would force a manual unbox on every assignment and lose the ability to represent a missing value as nil, so NSNumber is the honest choice.
Property attributes and reserved names
Two Objective-C details the generator handles for you.
Attributes. NSString and NSArray are mutable-subclassed, so the convention is copy (you get an immutable snapshot, not a reference someone can mutate underneath you). Everything else, custom classes and NSNumber, uses strong. All properties are nonatomic, as model objects almost always are.
Reserved names. Objective-C has reserved words that cannot be property names, and id and description are the common JSON keys that clash: id is a built-in type, and description is an NSObject method. The generator renames them to safe properties like theId and theDescription, and you map them back to the original keys in your parsing layer.
When you see id
A field that is only ever null, an empty array, or holds more than one unrelated type has no single Foundation type, so it falls back to id (or NSArray<id> * for a mixed array). That is a lack of evidence, not a bug. Populate those fields in the sample to get precise types, and reach for the JSON viewer to confirm the shape of a deeply nested payload before you convert.
Populating the classes from JSON
The @interface is the model; binding the parsed dictionary to it is a separate step. The manual route parses with NSJSONSerialization and assigns each property:
NSError *error = nil;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
Root *order = [Root new];
order.theId = dict[@"id"];
order.total = dict[@"total"];
On a larger app, a mapping library does this for you: Mantle (MTLJSONAdapter with a JSONKeyPathsByPropertyKey mapping) or JSONModel bind a dictionary to your @interface automatically, including the theId-to-id key mapping. Generate the classes here, then add the mapping layer your project prefers.
The gotchas that bite
- NSNumber, not scalar. JSON numbers arrive boxed. Read them with
integerValue,doubleValue, orboolValue; do not expect anintproperty to be filled automatically. - Reserved keys.
idanddescriptionbecometheIdandtheDescription; you must map them back to the real keys when binding. - copy for collections. Use
copyonNSStringandNSArrayso a mutable instance passed in cannot change under you. - Nil for missing. An absent key leaves the property
nil. Check fornilbefore using a value, since Objective-C messaging tonilis silent. - Two files. A full model is a
.hand a.m; this tool generates the@interfaceheader, which is the part worth automating.
Frequently asked questions
How do I convert JSON to an Objective-C class?
Paste the JSON into the JSON to Objective-C converter and it writes an @interface per object with typed @property declarations, inferring nested classes, typed NSArray, and Foundation types. Then bind a parsed NSDictionary to it manually or with Mantle or JSONModel.
Why are JSON numbers NSNumber in the output?
Because NSJSONSerialization decodes every number and boolean into an NSNumber. The property matches what you receive; read the value with integerValue, doubleValue, or boolValue.
What happens to a JSON key named id?
id is reserved in Objective-C, so it is renamed to the safe property theId, and you map it back to the id key in your binding layer.
Should I use Objective-C or Swift for new code?
New iOS and macOS code is usually Swift, where the counterpart is a Codable struct; see converting JSON to Swift. Objective-C generation is for existing codebases and SDKs that are still written in it.
For the format underneath all this, see the guide on what JSON is and the roundup of free JSON tools for the rest of the toolkit.
Leave a Reply