Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
iOS 5 introduced the NSJSONSerialization class, which is tremendously handy when you’re working with web services. All you need is a valid JSON object (namely an array or dictionary) whose components are also valid 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 *valueArray =
[@"val1 val2 val3" componentsSeparatedByString:@" "];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for (NSString *each in
[@"KeyA KeyB KeyC" componentsSeparatedByString:@" "])
dict setObject:valueArray forKey:each];
// Convert it to JSON
if ([NSJSONSerialization isValidJSONObject:dict])
{
NSData *data = [NSJSONSerialization
dataWithJSONObject:dict options:0 error:nil];
NSString *result = [[NSString alloc]
initWithData:data encoding:NSUTF8StringEncoding];
[self log: %@", result];
}