isValidJSONObject:
Returns a Boolean value that indicates whether a given object can be converted to JSON data.
+ (BOOL)isValidJSONObject:(id)obj
Parameters
- obj
- The object to test.
Return Value
YES
if obj can be converted to JSON data, otherwise NO
.
( NSJSONSerialization isValidJSONObject example )
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
id jsonObj = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
BOOL isValid = [NSJSONSerialization isValidJSONObject:jsonObj];
( NSJSONSerialization isValidJSONObject example )
NSDictionary* jsonDictionary = @{
@"firstName" : @"John",
@"lastName" : @"Smith",
@"age" : @(25),
@"address" : @{
@"streetAddress": @"21 2nd Street",
@"city" : @"New York",
@"state" : @"NY",
@"postalCode" : @"10021"
}
};
BOOL valid = [NSJSONSerialization isValidJSONObject:jsonDictionary];
if (valid) {
NSLog(@"Valid JSON");
} else {
NSLog(@"Invalid JSON");
}
( NSJSONSerialization isValidJSONObject example )
NSDictionary *blobData = [NSDictionary dictionaryWithObjectsAndKeys:
sendString,@"string",
nil];
NSString *blobString = [[NSString alloc]
initWithData:[NSJSONSerialization dataWithJSONObject:blobData options:kNilOptions error:&error]
encoding:NSUTF8StringEncoding];
NSLog(@"Blob Created: %@", blobString);
NSDictionary *requestData = [NSDictionary dictionaryWithObjectsAndKeys:
@"send_string",@"request_type",
[NSNumber numberWithInt:0],@"security_level",
@"ios",@"device_type",
//No Email Provided, This is just for testing
blobString,@"blob",
nil];
NSData *JSONRequestData = NULL;
if ([NSJSONSerialization isValidJSONObject:requestData]) {
NSLog(@"Proper JSON Object");
JSONRequestData = [NSJSONSerialization dataWithJSONObject:requestData options:kNilOptions error:&error];
}
else {
NSLog(@"requestData was not a proper JSON object");
return FALSE;
}
NSLog(@"%@",[[error userInfo] objectForKey:@"NSDebugDescription"]);
NSLog(@"%@",[[NSString alloc] initWithData:JSONRequestData encoding:NSUTF8StringEncoding]);