Recipe: Using JSON Serialization
The NSJSONSerialization
class is tremendously handy when you’re working with JSON-based web services. All you need is a valid JSON container (namely an array or a dictionary) whose components are also valid JSON objects, including strings, numbers, arrays, dictionaries, and NSNull
. Test an object’s validity with isValidJSONObject
, which returns YES
if the object can be safely converted to JSON format:
// Build a basic JSON object NSArray *array = @[@"Val1", @"Val2", @"Val3"]; NSDictionary *dict = @{@"Key 1":array, @"Key 2":array, @"Key 3":array}; // Convert it to JSON if ([NSJSONSerialization isValidJSONObject:dict]) { NSData *data = [NSJSONSerialization dataWithJSONObject:dict ...
Get The Core iOS Developer’s Cookbook, Fifth Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.