Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Chapter 15. Networking > One More Thing: Using JSON Serialization

One More Thing: Using JSON Serialization

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];
}


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint