TouchJSON, dealing with NSNull

前端 未结 3 1518
清酒与你
清酒与你 2020-11-29 06:50

Hi I am using TouchJSON to deserialize some JSON. I have been using it in the past and on those occasions I dealt with occurrences of NSNull manually. I would think the auth

3条回答
  •  日久生厌
    2020-11-29 07:14

    For another JSON library, but with the same issues, I've created the following category on NSDictionary:

    @implementation NSDictionary (Utility)
    
    // in case of [NSNull null] values a nil is returned ...
    - (id)objectForKeyNotNull:(id)key {
       id object = [self objectForKey:key];
       if (object == [NSNull null])
          return nil;
    
       return object;
    }
    
    @end
    

    Whenever I deal with JSON data from said library, I retrieve values like this:

    NSString *someString = [jsonDictionary objectForKeyNotNull:@"SomeString"];
    

    This way the code in my projects become a lot cleaner and at the same time I don't have to think about dealing with [NSNull null] values and the like.

提交回复
热议问题