Checking a null value in Objective-C that has been returned from a JSON string
<null>
is how the NSNull singleton logs. So:
if (tel == (id)[NSNull null]) {
// tel is null
}
(The singleton exists because you can't add nil
to collection classes.)
Checking a null value from Json response in Objective-C
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *error;
json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSLog(@"json.... %@",json);
id jsonObject = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:nil];
NSLog(@"jsonObject=%@", jsonObject);
NSDictionary *checkArray=[json valueForKey:@"ND"];
NSArray *tel = [checkArray valueForKey:@"FN"];
for (id photo in tel)
{
if (photo == [NSNull null])
{
// photo is null
}
else
{
// photo isn't null. It's an array
NSArray *innerPhotos = photo;
NSLog(@"photo... %@",innerPhotos);
}
}
cheDisk1=[checkArray valueForKey:@"LN"];
NSLog(@"FN =%@",tel);
[ContactTableview reloadData];
}
Checking a null value from Json response in Objective-C
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *error;
json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSLog(@"json.... %@",json);
id jsonObject = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:nil];
NSLog(@"jsonObject=%@", jsonObject);
NSDictionary *checkArray=[json valueForKey:@"ND"];
NSArray *tel = [checkArray valueForKey:@"FN"];
for (id photo in tel)
{
if (photo == [NSNull null])
{
// photo is null
}
else
{
// photo isn't null. It's an array
NSArray *innerPhotos = photo;
NSLog(@"photo... %@",innerPhotos);
}
}
cheDisk1=[checkArray valueForKey:@"LN"];
NSLog(@"FN =%@",tel);
[ContactTableview reloadData];
}
Identify NULL values in objective C
Foundation collections can only contain objects types (NSObject
subclasses). As such, in order to represent nil we use +[NSNull null]
. It just so happens that NSNull
's implementation of -description
returns <null>
and that's what you're seeing in the console.
Try comparing the result of -objectForKey
to [NSNull null]
instead.
how to check for null object returned in xcode
A JSON "null" value is converted to [NSNull null]
, which you can check
for with
if (text == [NSNull null]) ...
because it is a singleton.
Alternatively, you can check if the object contains the expected type, i.e. a string:
NSString *text = [obj objectForKey:@"BillingStreet"];
if ([text isKindOfClass:[NSString class]]) {
self.labelCustomerAddress.text = text;
} else {
self.labelCustomerAddress.text = @"no street";
}
This is more robust in the case that a server sends bad data, e.g. a number or an array instead of a string.
How can I check If I got null from json?
I believe most JSON parsers represent null
as [NSNull null]
.
Considering jsonDict
points to that single element in the array, then the following should work:
if ([jsonDict objectForKey:@"photo"] == [NSNull null]) {
// it's null
}
Edit based on comment: so jsonDict
, despite its name, is an array. In that case, rename jsonDict
to jsonArray
to avoid further confusion. Then, considering jsonArray
points to an array similar to the example posted in the question:
NSArray *photos = [jsonArray valueForKey:@"photo"];
for (id photo in photos) {
if (photo == [NSNull null]) {
// photo is null
}
else {
// photo isn't null
}
}
Further edit based on OP’s modified question:
NSArray *jsonArray = [string JSONValue];
NSArray *photos = [jsonArray valueForKey:@"photo"];
for (id photo in photos) {
if (photo == [NSNull null]) {
// photo is null
}
else {
// photo isn't null. It's an array
NSArray *innerPhotos = photo;
…
}
}
How do I test for null in NSDictionary from SBJSON?
When transferring data from JSON to a Cocoa collection, the NSNull
class is used to represent "no value", since Cocoa collections can't have empty slots. <null>
is how NSNull
prints itself.
To test for this, you can use someObject == [NSNull null]
. It's a singleton -- there's only one instance of NSNull
per process -- so pointer comparison works, although you may prefer to follow the usual Cocoa comparison convention and use [someObject isKindOfClass:[NSNull class]]
.
You're getting the crash because you're sending integerValue
to that NSNull
object. NSNull
doesn't respond to integerValue
and raises an exception.
Parsing Json to object giving null Value
I got the very perfect solution for your question which works fine now.Please check the below answer
- (void)callAPI
{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:@"GET"];
[request setURL:[NSURL URLWithString:@"https://dl.dropboxusercontent.com/s/2iodh4vg0eortkl/facts.json"]];
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:
^(NSData * data,
NSURLResponse * response,
NSError * error) {
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(@"jsonString is: %@", jsonString);
NSData *dataCon = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
id jsonVal = [NSJSONSerialization JSONObjectWithData:dataCon options:0 error:nil];
if([jsonVal isKindOfClass:[NSDictionary class]]) {
NSLog(@"The response starts with NSDictionary");
NSArray *arrJsonVal = [jsonVal objectForKey:@"rows"];
NSMutableArray *arrTitle = [[NSMutableArray alloc]init];
NSMutableArray *arrDesc = [[NSMutableArray alloc]init];
NSMutableArray *arrImage = [[NSMutableArray alloc]init];
for(NSDictionary *dict in arrJsonVal) {
NSString *strTitle = [dict objectForKey:@"title"];
NSString *strDesc = [dict objectForKey:@"description"];
NSString *strImage = [dict objectForKey:@"imageHref"];
[arrTitle addObject:strTitle];
[arrDesc addObject:strDesc];
[arrImage addObject:strImage];
}
NSLog(@"arrTitle is - %@",arrTitle);
NSLog(@"arrDesc is - %@",arrDesc);
NSLog(@"arrImage is - %@",arrImage);
}else {
NSLog(@"The response starts with NSArray");
}
}] resume];
}
The Printed results are
After that
Then Array results are
Finally the results are
swift how can I check for NULL values coming from Json
You just need to conditionally cast your dictionary value to String and use the Nil Coalescing Operator ??
to assign "0"
in case of failure null
:
let vote_status = Stream["vote_status"] as? String ?? "0"
Condition for checking NOT null value for NSString in Objective C
Try the following code
id phoneNo = [personDict objectForKey:kPhoneKey];
if( phoneNo && ![phoneNo isKindOfClass:[NSNull class]] )
{
NSString *tempPhone = [NSString stringWithFormat:@"%@", [personDict objectForKey:kPhoneKey]];
NSLog(@"NSString *tempPhone = %@",tempPhone);
}
else
{
NSLog(@"NSString *tempPhone is null");
}
Related Topics
How to Xcodebuild a Static Library with Bitcode Enabled
Add Shadow on Uiview Using Swift 3
Warning: Attempt to Present * on * Whose View Is Not in the Window Hierarchy - Swift
Automatic Otp Verification in iOS
How to Programmatically Add a Proxy to an Nsurlsession
Phonegap iOS 5.1 and Localstorage
Application:Didreceiveremotenotification:Fetchcompletionhandler Not Called
Firebase Fcm Silent Push Notifications for iOS
How to Reference Instance Function When Calling Sequencetype.Foreach
Div Scrolling Freezes Sometimes If I Use -Webkit-Overflow-Scrolling
How to Post Nested JSON by Swiftyjson and Alamofire
How to Get Commoncrypto/Commoncrypto File From
Swift - How to Save Memory Using Alamofireimage/Imageshack
iOS 9 '-Webkit-Overflow-Scrolling:Touch' and 'Overflow: Scroll' Breaks Scrolling Capability
Which Is the Best Way to Estimate Measure of Photographed Things