Sunday, May 12, 2013

NSJSONSerialization dataWithJSONObject example ios

dataWithJSONObject: options: error:

Returns JSON data from a Foundation object.
+ (NSData *)dataWithJSONObject:(id)obj options:(NSJSONWritingOptions)opt error:(NSError **)error
The object from which to generate JSON data.
Options for creating the JSON data.( NSJSONSerialization dataWithJSONObject example )
See “NSJSONWritingOptions” for possible values. Pass 0 to specify no options.
If an error occurs, upon return contains an NSError object that describes the problem.
Return Value
JSON data for obj, or nil if an error occurs. The resulting data is a encoded in UTF-8.
Discussion( NSJSONSerialization dataWithJSONObject example )
If obj will not produce valid JSON, an exception is thrown.
Setting the NSJSONWritingPrettyPrinted option will generate JSON with whitespace designed to make the output more readable. If that option is not set, the most compact possible JSON will be generated.
( NSJSONSerialization dataWithJSONObject example )
NSString *nid = @"";
NSString *vocab = @"";
NSString *inturl = @"testoverview";
NSString *mail = @"";
NSString *md5pw = @"4d57e7ef1b7c3f431aca424764e9d786";

NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                nid, @"nid", 
                                vocab, @"vocab",
                                inturl, @"inturl",
                                mail, @"mail",
                                md5pw, @"md5pw",nil];

NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:NSJSONWritingPrettyPrinted error:&error];
NSString *resultAsString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"jsonData as string:\n%@", resultAsString);
( NSJSONSerialization dataWithJSONObject example )
NSDictionary *menuDictionary = [self dictionaryFromMenu:[[DataStore singleton] getHomeMenu]]; 

NSError *err;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:menuDictionary options:NSJSONWritingPrettyPrinted error:&err];

NSLog(@"JSON = %@", [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
( NSJSONSerialization dataWithJSONObject example )
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:info 
          options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

    // Start request
    NSURL *url = [NSURL URLWithString:@""];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    [request setPostValue:jsonString forKey:@"songs"];
    [request setDelegate:self];
    [request startAsynchronous];