ios 检查从 JSON 字符串返回的 Objective-C 中的空值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4839355/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 18:42:34  来源:igfitidea点击:

Checking a null value in Objective-C that has been returned from a JSON string

iosobjective-cjson

提问by Chris

I have a JSONobject that is coming from a webserver.

我有一个来自网络服务器的JSON对象。

The log is something like this:

日志是这样的:

{          
   "status":"success",
   "UserID":15,
   "Name":"John",
   "DisplayName":"John",
   "Surname":"Smith",
   "Email":"email",
   "Telephone":null,
   "FullAccount":"true"
}

Note the Telephone is coming in as null if the user doesn't enter one.

请注意,如果用户未输入电话,则电话将作为空输入。

When assigning this value to a NSString, in the NSLogit's coming out as <null>

当将此值分配给 a 时NSStringNSLog它会作为<null>

I am assigning the string like this:

我正在分配这样的字符串:

NSString *tel = [jsonDictionary valueForKey:@"Telephone"];

What is the correct way to check this <null>value? It's preventing me from saving a NSDictionary.

检查此<null>值的正确方法是什么?它阻止我保存NSDictionary.

I have tried using the conditions [myString length]and myString == niland myString == NULL

我一直在使用的条件尝试[myString length]myString == nilmyString == NULL

Additionally where is the best place in the iOS documentation to read up on this?

此外,iOS 文档中阅读此内容的最佳位置在哪里?

回答by Wevah

<null>is how the NSNull singleton logs. So:

<null>是 NSNull 单例记录的方式。所以:

if (tel == (id)[NSNull null]) {
    // tel is null
}

(The singleton exists because you can't add nilto collection classes.)

(单例存在是因为您无法添加nil到集合类。)

回答by Flea

Here is the example with the cast:

这是演员表的例子:

if (tel == (NSString *)[NSNull null])
{
   // do logic here
}

回答by Nitin Gohel

you can also check this Incoming String like this way also:-

您也可以像这样检查此传入字符串:-

if(tel==(id) [NSNull null] || [tel length]==0 || [tel isEqualToString:@""])
{
    NSlog(@"Print check log");
}
else
{  

    NSlog(@Printcheck log %@",tel);  

}

回答by Kyle C

If you are dealing with an "unstable" API, you may want to iterate through all the keys to check for null. I created a category to deal with this:

如果您正在处理“不稳定”的 API,您可能需要遍历所有键以检查是否为 null。我创建了一个类别来处理这个问题:

@interface NSDictionary (Safe)
-(NSDictionary *)removeNullValues;
@end

@implementation NSDictionary (Safe)

-(NSDictionary *)removeNullValues
{
    NSMutableDictionary *mutDictionary = [self mutableCopy];
    NSMutableArray *keysToDelete = [NSMutableArray array];
    [mutDictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        if (obj == [NSNull null]) 
        {
            [keysToDelete addObject:key];
        }
    }];
    [mutDictinary removeObjectsForKeys:keysToDelete];
    return [mutDictinary copy];
}
@end

回答by kjoelbro

The best answer is what Aaron Hayman has commented below the accepted answer:

最佳答案是亚伦·海曼 (Aaron Hayman) 在接受的答案下方评论的内容:

if ([tel isKindOfClass:[NSNull class]])

It doesn't produce a warning :)

它不会产生警告:)

回答by Brian

if you have many attributes in json, using ifstatement to check them one by one is troublesome. What even worse is that the code would be ugly and hard to maintain.

如果json中有很多属性,用if语句一一检查就麻烦了。更糟糕的是,代码会很丑陋且难以维护。

I think the better approach is creating a category of NSDictionary:

我认为更好的方法是创建一个类别NSDictionary

// NSDictionary+AwesomeDictionary.h

#import <Foundation/Foundation.h>

@interface NSDictionary (AwesomeDictionary)
- (id)validatedValueForKey:(NSString *)key;
@end

// NSDictionary+AwesomeDictionary.m

#import "NSDictionary+AwesomeDictionary.h"

@implementation NSDictionary (AwesomeDictionary)
- (id)validatedValueForKey:(NSString *)key {
    id value = [self valueForKey:key];
    if (value == [NSNull null]) {
        value = nil;
    }
    return value;
}
@end

after importing this category, you can:

导入此类别后,您可以:

[json validatedValueForKey:key];

回答by Yunus Nedim Mehel

I usually do it like this:

我通常这样做:

Assuma I have a data model for the user, and it has an NSString property called email, fetched from a JSON dict. If the email field is used inside the application, converting it to empty string prevents possible crashes:

Assuma 我有一个用户数据模型,它有一个名为 email 的 NSString 属性,从 JSON dict 中获取。如果在应用程序内部使用电子邮件字段,将其转换为空字符串可以防止可能的崩溃:

- (id)initWithJSONDictionary:(NSDictionary *)dictionary{

    //Initializer, other properties etc...

    id usersmail = [[dictionary objectForKey:@"email"] copy];
    _email = ( usersmail && usersmail != (id)[NSNull null] )? [usersmail copy] : [[NSString      alloc]initWithString:@""];
}

回答by Segev

In Swift you can do:

在 Swift 中,您可以执行以下操作:

let value: AnyObject? = xyz.objectForKey("xyz")    
if value as NSObject == NSNull() {
    // value is null
    }

回答by Segev

I tried a lot method, but nothing worked. Finally this worked for me.

我尝试了很多方法,但没有任何效果。最后这对我有用。

NSString *usernameValue = [NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"usernameKey"]];

if ([usernameValue isEqual:@"(null)"])
{
     // str is null
}

回答by Gajendra K Chauhan

if([tel isEqual:[NSNull null]])
{
   //do something when value is null
}