JSON to Objective-C

Generate @interface blocks, typed properties and dictionary initialisers from a sample response.

JSON
Objective-C
Runs locally in your browser

About the JSON to Objective-C

Objective-C code bases still back plenty of shipping iOS and macOS apps, and they usually wrap every response in a model object rather than passing dictionaries around. This generator writes that layer: an @interface per object shape with typed properties, an initWithDictionary: initialiser that reads each key, and a toDictionary method for sending the object back.

Property attributes follow the conventions the compiler expects. Strings are declared copy so a mutable string passed in cannot change underneath you, object references are strong, and scalars are assign. Numbers arrive from a dictionary boxed in NSNumber, so the initialiser calls integerValue, doubleValue or boolValue to unbox them into NSInteger, double and BOOL.

Lists become NSArray with a lightweight generic, and a list of objects gets a loop that builds each element through its own initialiser. Nullability annotations are wrapped in NS_ASSUME_NONNULL_BEGIN and NS_ASSUME_NONNULL_END, with only the keys that were null or absent in the sample marked nullable, which is exactly the information Swift needs when it imports the header.

A two letter class prefix is applied to every generated name, the long standing convention for avoiding collisions in a language without namespaces. Untick the implementation switch to keep only the header. For Swift instead, use JSON to Swift.

How to use

  1. Paste a JSON response, or press Sample to load a music track.
  2. Set the Class prefix your project uses and name the root class.
  3. Untick Include implementation when you only need the header file.
  4. Copy the result, or download it and split the interface and implementation into .h and .m files.

Common questions

Why is the whole file one download?
The interfaces come first and the implementation follows after a marker comment, so you can cut at that line and paste the halves into your .h and .m files.
How are numbers handled?
A dictionary always hands back NSNumber, so the initialiser unboxes with integerValue, doubleValue or boolValue into the matching scalar property.
What do the nullability annotations do?
They mark which properties may be nil. Swift uses that information when importing the header, so an audited class maps onto optionals correctly.
Can I use these classes with NSJSONSerialization?
Yes. Feed the dictionary that NSJSONSerialization returns straight into initWithDictionary: and the object graph is built for you.