JSON to Objective-C: typed model classes
Many iOS and macOS apps still have Objective-C model layers, and mapping NSJSONSerialization dictionaries into them by hand is repetitive. This JSON to Objective-C generator writes the classes for you: a header section with @interface declarations and @property attributes, and an implementation section. Every class gets the QT prefix, following the Objective-C convention of prefixing class names to avoid collisions, since the language has no namespaces.
Example
{ "id": 42, "title": "Write docs", "done": false,
"owner": { "name": "Ada", "email": null },
"subtasks": [ { "title": "Outline", "estimate": 2 }, { "title": "Draft" } ] }
NS_ASSUME_NONNULL_BEGIN
@interface QTTask : NSObject
@property (nonatomic, assign) NSInteger identifier;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, assign) BOOL isDone;
@property (nonatomic, strong) QTOwner *owner;
@property (nonatomic, copy) NSArray<QTSubtask *> *subtasks;
@end
@interface QTSubtask : NSObject
@property (nonatomic, copy) NSString *title;
@property (nonatomic, nullable, strong) NSNumber *estimate;
@end
NS_ASSUME_NONNULL_END
Objective-C conventions applied
- Reserved names are avoided:
idbecomesidentifier, becauseidis an Objective-C type. - Boolean getters get an
isprefix (isDone), following Cocoa naming. - Property attributes follow Cocoa practice:
copyfor strings and arrays,strongfor nested objects,assignfor scalars. - Optional numbers become
NSNumber *markednullable, since a scalarNSIntegercannot represent "missing". - Nullability is declared with
NS_ASSUME_NONNULL_BEGIN, which also produces clean optionals when the classes are used from Swift. - Lightweight generics such as
NSArray<QTSubtask *> *keep collection types visible to Xcode and Swift.
Type mapping
Whole numbers become NSInteger and decimals double when they are always present; strings are NSString *, booleans BOOL, arrays NSArray<T *> *, and nested objects their own prefixed classes. Dates stay NSString *; convert them with NSISO8601DateFormatter. An array that mixes numbers and strings is typed as NSArray<id> *, so check the element class at runtime before using it.
Parsing with the full output
Without Types only, the implementation includes property-name maps and methods to build objects from dictionaries or JSON strings, for example [QTTask fromJSON:json encoding:NSUTF8StringEncoding error:&error], and to write them back with toJSON. Nested objects and arrays of objects are converted recursively. The output is split into a QTTask.h part and a QTTask.m part, marked with comments; save them as two files.
If you are writing new code, Swift's Codable is simpler; try JSON to Swift. Format the generated files with the Objective-C Formatter. Generation runs in your browser.