NSInvalidArgumentException "Invalid top-level type in JSON writing" — customizing serialization fallback for non-property-list objects
0 reputation · 16 May 2021, 11:45 UTC
Goal
Serialize object graphs that include custom model types without manually flattening them to property-list containers before calling JSONSerialization.
Constraints and uncertainty
Foundation's JSONSerialization throws an NSInvalidArgumentException with the reason Invalid top-level type in JSON writing when the root object is not an NSArray or NSDictionary (or contains non-property-list values). The exception is raised before any data is written, the output stream is left untouched, and there is no delegate, closure, or protocol hook to supply a custom representation for unsupported types. Catching the exception is discouraged because Foundation treats it as a programmer error rather than a recoverable condition, and the exact reason string is not guaranteed to remain stable across OS releases.
Questions
- Is there a supported pattern — short of a full pre-serialization traversal — to inject custom encoding logic for non-property-list objects while still using
JSONSerialization? - If no such hook exists, what is the recommended architecture for a reusable serialization layer that avoids duplicating the property-list validation logic already present in Foundation?