使用JSON中返回的空数据时,应用程序崩溃

时间:2014-03-28 09:56:46

标签: ios json

{
   "prodid":"32",
   "prodname":"Casserole Stainless steel",
   "imageurl":"bimg51590b400f339.jpg"
},
{
   "prodid":"783",
   "prodname":   **null**
   "imageurl":"simg51b02ba3a9dcd.jpg"
},
{
   "prodid":"641",
   "prodname":"EVAPORATIVE COOLING DOG PAD",
   "imageurl":"simg5184dd5b21d0b.jpg"
}

 if ([response count]>0) {
    for (NSUInteger i =0; i < [response count]; i++) {
        self.workingEntry = [[AppRecord alloc]init];
        self.workingEntry.ID = [[response objectAtIndex:i] valueForKey:@"prodid"];
        NSString * name = [[[response objectAtIndex:i]objectForKey:@"prodname"]retain];
        self.workingEntry.name = name;

当“prodname”字段为空时发生崩溃。我怎么阻止这个?

3 个答案:

答案 0 :(得分:1)

您可以在分配值之前运行循环

for(NSDictionary *product in response) {
    for(id key in [product allKeys]) {
        if([product valueForKey:key] == (id)[NSNull null]) {
            [product setValue:@"" forKey:key];

            //If you want to delete that null object
            //[response removeObject:product]
        }
    }
}

它将使用@“”空NSString删除所有Null对象,因此在分配或使用时不会崩溃。

答案 1 :(得分:1)

   if ([response count]>0) {
    for (NSUInteger i =0; i < [response count]; i++) {
        self.workingEntry = [[AppRecord alloc]init];
        self.workingEntry.ID = [[response objectAtIndex:i] valueForKey:@"prodid"];
      if(![[[response objectAtIndex:i]objectForKey:@"prodname"] isEqual:[NSNull null]])
      {
        NSString * name = [[response objectAtIndex:i]objectForKey:@"prodname"];
       }
     else
     {
      NSSTring *name = @"";
     }

        self.workingEntry.name = name;
    }
  }

答案 2 :(得分:0)

NSJSONSerialization将JSON中的Null转换为数组和字典中的NSNull实例。当您开始像字符串或数字一样处理它们时,这可能会导致问题。

我使this category在序列化期间删除它们,或者从字典或数组递归后序列化。它可以通过Cocapods获得。