Ios 如何检查json对象是否包含<;空>;?

Ios 如何检查json对象是否包含<;空>;?,ios,objective-c,iphone,json,ipad,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)

通过在我的应用程序中发出网络请求,我从服务器获得了一个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";

              }

}
试试这个:

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

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

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

创建
NSDictionary
Category
,并在其中添加以下方法,该方法将dictionary中每个键的null值替换为空字符串

- (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];
}
用法: [yourJSONDictionary ByReplacingNullSwithString]

阅读有关iOS和中类别的更多信息


我想你把逻辑搞糊涂了。我试图忠实于您的代码,但如果以下内容不是您想要的,请告诉我:

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";
    }
}

以下是我为我的项目编写的几种方法,请尝试:

/*!
 *  @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
字符串、数组或对象传递给适当的方法,该方法就会为您清理它。

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

- (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、不需要值、是否需要空字符串,当我的假设错误时,这些方法会向我发出警告(但总是返回一些不会中断的内容)

检查
if([user\u post.username length]>=1)
使用
isEqual
if([user\u post.username isEqual:[NSNull null null]])
同样
iskindof类
也应该起作用。在第一行,我想你是想测试
[dict\u user\u info objectForKey:@“name”]
,看看它是否
[NSNull null]
.Casting
[NSNull null]
既错误又无用。它什么都没用。为什么!==而不是老好人!=@Avi:需要一些强制转换,因为编译器不允许您比较NSString*和NSNull*。我将强制转换为id(以避免给人留下[NSNull]可能是NSString的印象)。我确实同意强制转换到
id
更好。强制转换
NSNull*
而不是
NSString*
,这将解决compliler在我的构建中抱怨
something==[NSNull null]
@Avi的问题,如果编译器发出警告,它不允许:-)(严格的零警告策略)。您需要解释为什么您的代码示例比其他代码示例更好。到目前为止,由于缺乏解释,您的答案已自动标记为低质量。
user_post.username = [dict_user_info jsonStringForKey:@"name"] ?: @"username";