如何检查json对象是否包含<null>?

时间:2015-11-25 07:56:40

标签: ios objective-c iphone json ipad

我通过在我的应用中发出网络请求从服务器获得 Json 。我在 Json 对象中的某些键获得 if(!(user_post.username==(id)[NSNull null]) ) { user_post.username=[dict_user_info objectForKey:@"name"]; if(user_post.username!=nil) { ser_post.username=[dict_user_info objectForKey:@"name"]; } else { user_post.username=@"Username"; } } 值。我如果收到这种类型的回复,应用程序会崩溃。请告诉我如何验证&gt;?

我试过这个,但它并不是一直都有效。

POST https://www.googleapis.com/youtube/v3/videos/rate?id=b_bJQgZdjzo&rating=like&oauth_token={YOUR_accessTOken}

7 个答案:

答案 0 :(得分:1)

考虑测试null的值,这样你的程序就不会崩溃。像这样:

if([dict_user_info objectForKey:@"name"] != [NSNull null])
{
    ser_post.username=[dict_user_info objectForKey:@"name"];
}

答案 1 :(得分:0)

创建NSDictionary - (NSDictionary *)dictionaryByReplacingNullsWithStrings { const NSMutableDictionary *replaced = [self mutableCopy]; const id nul = [NSNull null]; const NSString *blank = @""; for(NSString *key in self) { const id object = [self objectForKey:key]; if(object == nul || object == NULL) { //pointer comparison is way faster than -isKindOfClass: //since [NSNull null] is a singleton, they'll all point to the same //location in memory. [replaced setObject:blank forKey:key]; } } return [replaced copy]; } 并在其中添加以下方法,该字符为字典中的每个键替换空字符串的空值。

simplexml_load_file()

用法: [yourJSONDictionary dictionaryByReplacingNullsWithStrings];

  

详细了解iOS Tutorial 1Tutorial 2

中的类别

答案 2 :(得分:0)

yourJsonObject = [myDic valueforkey@"key"];
if(yourJsonObject != [NSNull null])
{
 //not null
}
** you can also check whether object exist or not 
if(yourJsonObject)
{
//exist
}

答案 3 :(得分:0)

我认为你混淆了你的逻辑。我试图坚持你的代码,但如果以下不是你想要的,请告诉我:

if (dict_user_info[@"name"] != nil && [dict_user_info[@"name"] isKindOfClass:[NSNull class]] == NO) {
    user_post.username = dict_user_info[@"name"];

    if (user_post.username != nil) {
        ser_post.username = user_post.username;
    } else {
        user_post.username = @"Username";
    }
}

答案 4 :(得分:0)

这些是我为我的项目编写的几种方法,试试它们:

/*!
 *  @brief  Makes sure the object is not NSNull or NSCFNumber, if YES, converts them to NSString
 *  @discussion Sometimes JSON responses can contain NSNull objects, which does not play well with Obj-C. So when you access a value from a JSON and expect it to be an NSString, pass it through this method just to make sure thats the case.
 *  @param str The object that is supposed to be a string
 *  @return The object cleaned of unacceptable values
 */
+ (NSString *)cleanedJsonString:(id)str
{
  NSString *formattedstr;
  formattedstr = (str == [NSNull null]) ? @"" : str;
  if ([str isKindOfClass:[NSNumber class]]) {
    NSNumber *num = (NSNumber*) str;
    formattedstr = [NSString stringWithFormat:@"%@",num];
  }
  return formattedstr;
}
/*!
 *  @brief  Makes Sure the object is not NSNull
 *  @param obj Sometimes JSON responses can contain NSNull objects, which does not play well with Obj-C. So when you access a value from a JSON ( NSArray, NSDictionary or NSString), pass it through this method just to make sure thats the case.
 *  @return The object cleaned of unacceptable values
 */
+ (id)cleanedObject:(id)obj
{
  return (obj == [NSNull null]) ? nil : obj;
}
/*!
 *  @brief A JSON cleaning function for NSArray Objects.
 *  @discussion Sometimes JSON responses can contain NSNull objects, which does not play well with Obj-C. So when you access a value from a JSON and expect it to be an NSArray, pass it through this method just to make sure thats the case. This method first checks if the object itself is NSNull. If not, then it traverses the array objects and cleans them too.
 *  @param arr The Objects thats supposed to be an NSArray
 *  @return The NSNull Cleaned object
 */
+ (NSArray *)cleanedJsonArray:(id)arr
{
  if (arr == [NSNull null]) {
    return [[NSArray alloc] init];
  }
  else
  {
    NSMutableArray *arrM = [(NSArray*)arr mutableCopy];
    int i=0;
    for (id __strong orb in arrM)
    {
        if (orb == [NSNull null])
        {
            [arrM removeObjectAtIndex:i];;
        }
        i++;
    }
    return arrM;
  }
}

只需将JSON字符串,数组或对象传递给相应的方法,该方法就会为您清理它。

答案 5 :(得分:0)

帮自己一个忙,写一个处理这个问题的方法并将其放入扩展中。像

- (NSString*)jsonStringForKey:(NSString*)key
{
    id result = self [key];
    if (result == nil || result == [NSNull null]) return nil;
    if ([result isKindOfClass:[NSString class]]) return result; 

    NSLog (@"Key %@: Expected string, got %@", key, result);
    return nil;
}

你甚至可以添加一些接受NSNumber *结果的代码并将它们变成字符串,如果那是你的服务器返回的(这里的一些海报有问题,他的服务器将服装尺寸改为像40这样的数字或字符串如“40- 42“这使得这样的东西很有用)。

然后你的代码变成一条可读行

user_post.username = [dict_user_info jsonStringForKey:@"name"] ?: @"username";

我实际上使用了几种略有不同的方法,具体取决于我是否期望null,期望没有值,期望是否为空字符串,这会在我的假设错误时给出警告(但总是返回不会中断的内容)。

答案 6 :(得分:-2)

试试这个:

if(!(user_post.username == (NSString *)[NSNull null]) )