【问题标题】:How can I check If I got null from json?如何检查我是否从 json 得到 null?
【发布时间】:2011-05-19 04:00:43
【问题描述】:

这是我从 JSON 得到的

[{"照片":null}]

我使用这个代码

NSMutableArray *jPhoto = [NSMutableArray arrayWithArray:(NSArray *)[jsonDict valueForKey:@"photo"]];

如果我想使用 if() 如何检查它?

编辑

这里是 JSON 数据

   [{"photo":
              [{"image":"http:\/\/www.yohyeh.com\/upload\/shisetsu\/13157\/photo\/1304928459.jpg","title":"test picture","content":"this is description for test picture.\r\n\u8aac\u660e\u6587\u306a\u306e\u306b\u30fb\u30fb\u30fb\u30fb\u30fb\u30fb\u30fb\u30fb\u30fb\u30fb\u30fb\u30fb"}
              ,{"image":"http:\/\/www.yohyeh.com\/upload\/shisetsu\/13157\/photo\/1304928115.jpg","title":"nothing","content":"iMirai"}
              ,{"image":"http:\/\/www.yohyeh.com\/upload\/shisetsu\/13157\/photo\/1303276769.jpg","title":"iMirai","content":"Staff"}]}
  ]

这是我的 JSON 解析器

NSError *theError = nil;     
    NSString *URL = [NSString stringWithFormat:@"http://www.yohyeh.com/apps/get_sub_detail.php?id=%@&menu=photo",g_id];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URL]];
    NSURLResponse *theResponse =[[[NSURLResponse alloc]init] autorelease];
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&theError];   
    NSMutableString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    NSDictionary *jsonDict = [string JSONValue];

感谢帮助

【问题讨论】:

  • 您使用的是哪个 JSON 解析器?
  • 我使用 JSON 框架。照片中有很多属性,不仅仅是图片链接,还有很多东西。我不确定我是否正确。但我认为 NSMutable 还可以。或不 ???请指导我。 :)
  • 如果您发布一个更完整的 JSON 数据示例以及您用于解析它们的代码,将会有所帮助。
  • 哦,这个。如果我使用 NSMutableArray。我可以使用这个 if([jPhoto objectAtIndex:0]== [NSNull null]) { } 并且它可以工作。感谢您的帮助。但我仍在等待巴伐利亚的指南。 :)

标签: iphone objective-c ios json nsmutablearray


【解决方案1】:

我相信大多数 JSON 解析器将 null 表示为 [NSNull null]

考虑到 jsonDict 指向数组中的单个元素,那么以下应该可以工作:

if ([jsonDict objectForKey:@"photo"] == [NSNull null]) {
    // it's null
}

根据评论编辑:所以jsonDict,尽管它的名字,是一个数组。在这种情况下,请将 jsonDict 重命名为 jsonArray 以避免进一步混淆。然后,考虑jsonArray 指向一个类似于问题中发布的示例的数组:

NSArray *photos = [jsonArray valueForKey:@"photo"];
for (id photo in photos) {
    if (photo == [NSNull null]) {
        // photo is null
    }
    else {
        // photo isn't null
    }
}

根据 OP 修改后的问题进一步编辑:

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

【讨论】:

  • 哦,它崩溃了。这是一个错误 -[__NSArrayM objectForKey:]: unrecognized selector sent to instance 0x58938e0 2011-05-19 11:10:47.131 iLife[2012:207] *** Terminating app由于未捕获的异常 'NSInvalidArgumentException',原因:'-[__NSArrayM objectForKey:]: unrecognized selector sent to instance 0x58938e0'
  • 这意味着jsonDict 是一个数组,而不是字典。请参阅我对您的问题的最后评论。
【解决方案2】:

如果负载是具有可能值的复杂 JSON 结构,宏会很有帮助。

#define SET_IF_NOT_NULL(TARGET, VAL) if(VAL != [NSNull null]) { TARGET = VAL; }

宏可以像这样引用

SET_IF_NOT_NULL(myRecord.name, [jsonData objectForKey:@"name"]);

【讨论】:

  • 我可以知道你所说的 myrecord.name 是什么意思
  • 非常好的解决方案,而不是为 NSObject 和过多的 'if' 条件创建类别。投票,@Ramesh
  • 投了赞成票!尝试使用此宏解析双精度值时出现错误。 Invalid operands to binary expression ('double _Nullable' and 'NSNull * _Nonnull')Invalid operands to binary expression ('double _Nullable' and 'void *') 我该如何解决这个问题?
【解决方案3】:

解决这个问题没有简单的方法,但我这样做的方法是在 NSObject 上创建一个类别:

@interface NSObject (NotNull)

- (instancetype)notNull;

@end

这样实现:

@implementation NSObject (NotNull)

- (instancetype)notNull
{
    return self;
}

@end

@implementation NSNull (NotNull)

- (instancetype)notNull
{
    return nil;
}

@end

然后您可以将notNull 发送到JSON 字典中的任何可选对象,您将获得nil 如果它是 NSNull,则返回。否则,您将获得原始对象。例如:

self.parentIdentifier = [dictionary[@"parent_id"] notNull];

【讨论】:

  • 爱它!为了更加安全,我刚刚在方法名称中添加了一个三字母前缀 :)
  • @joerick 该解决方案正在工作,但我没有得到这背后的逻辑。如果可能的话,请解释它的工作流程,这将是有帮助的。谢谢。
【解决方案4】:

尝试检查[jPhoto count][NSNull null]

【讨论】:

    【解决方案5】:

    希望这会有所帮助。

    -(NSMutableDictionary *)jsonCheckforNull:(NSMutableDictionary *)json{

    NSMutableDictionary* strongjson=[json mutableCopy];

    for (NSString *ktr in json) {
    
        NSObject *str=[json objectForKey:ktr];
    
        if ([str isKindOfClass:[NSArray class]]) {
            if (!(str==[NSNull null])) {
                NSArray *temp = [json allKeysForObject:str];
                str=[[self ArrayCheckforNull:(NSMutableArray*)str]mutableCopy];
                NSString *key = [temp objectAtIndex:0];
                [strongjson removeObjectForKey:key];
                [strongjson setObject:str forKey:key];
            }
            else
            {
                NSArray *temp = [strongjson allKeysForObject:str];
                NSString *key = [temp objectAtIndex:0];
                [strongjson removeObjectForKey:key];
                [strongjson setObject:@"-----" forKey:key];
            }
    
        }
        else if ([str isKindOfClass:[NSDictionary class]]) {
            if (!(str==[NSNull null])) {
                str=[[self jsonCheckforNull:str]mutableCopy];
                NSArray *temp = [strongjson allKeysForObject:str];
                NSString *key = [temp objectAtIndex:0];
                [strongjson removeObjectForKey:key];
                [strongjson setObject:str forKey:key];
            }
            else
            {
                NSArray *temp = [strongjson allKeysForObject:str];
                NSString *key = [temp objectAtIndex:0];
                [strongjson removeObjectForKey:key];
                [strongjson setObject:@"-----" forKey:key];
            }
    
        }
    
        else {
    
            if (str ==[NSNull null]) {
                NSArray *temp = [strongjson allKeysForObject:str];
                NSString *key = [temp objectAtIndex:0];
                [strongjson removeObjectForKey:key];
                [strongjson setObject:@"----" forKey:key];
            }
    
        }
    
    }
    return strongjson;
    

    }

    -(NSMutableArray *)ArrayCheckforNull:(NSMutableArray *)arr{

    NSObject *str;
    NSMutableArray* strongArray=[[[NSMutableArray alloc]initWithArray:arr]mutableCopy];
    for (str in arr)
    {
    
        if ([str isKindOfClass:[NSArray class]]) {
            if (!(str==[NSNull null])) {
                str=[[self ArrayCheckforNull:(NSMutableArray *)str]mutableCopy];
                [strongArray removeObjectAtIndex:0];
                [strongArray addObject:str];
            }
            else
            {
                [strongArray removeObject:str];
                [strongArray addObject:@"----"];
    
            }
    
        }
        else if ([str isKindOfClass:[NSDictionary class]]) {
            if (!(str==[NSNull null])) {
                str=[[self jsonCheckforNull:(NSMutableDictionary*)str]mutableCopy];
                [strongArray removeObjectAtIndex:0];
                [strongArray addObject:str];
    
            }
            else
            {
                [strongArray removeObject:str];
                [strongArray addObject:@"----"];
            }
    
        }
    
        else {
    
            if (str ==[NSNull null]) {
                [strongArray removeObject:str];
                [strongArray addObject:@"----"];
            }
    
    
        }
    
    }
    return strongArray;
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-31
      • 1970-01-01
      相关资源
      最近更新 更多