Removing nulls from a JSON structure recursively

后端 未结 4 1992
忘了有多久
忘了有多久 2021-01-05 22:46

I\'m frequently finding the need to cache data structures created by NSJSONSerialization to disk and as -writeToFile fails if there are nulls, I ne

4条回答
  •  没有蜡笔的小新
    2021-01-05 23:46

    Here's the code I'm using to clean up my JSON calls, seems to work well but, since there's some processing overhead involved I really only use it in situations where I can't do the null handling on the server. NSNull crashes is far and away our biggest app crash problem.

    + (id)cleanJsonToObject:(id)data {
        NSError* error;
        if (data == (id)[NSNull null]){
            return [[NSObject alloc] init];
        }
        id jsonObject;
        if ([data isKindOfClass:[NSData class]]){
            jsonObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
        } else {
            jsonObject = data;
        }
        if ([jsonObject isKindOfClass:[NSArray class]]) {
            NSMutableArray *array = [jsonObject mutableCopy];
            for (int i = array.count-1; i >= 0; i--) {
                id a = array[i];
                if (a == (id)[NSNull null]){
                    [array removeObjectAtIndex:i];
                } else {
                    array[i] = [self cleanJsonToObject:a];
                }
            }
            return array;
        } else if ([jsonObject isKindOfClass:[NSDictionary class]]) {
            NSMutableDictionary *dictionary = [jsonObject mutableCopy];
            for(NSString *key in [dictionary allKeys]) {
                id d = dictionary[key];
                if (d == (id)[NSNull null]){
                    dictionary[key] = @"";
                } else {
                    dictionary[key] = [self cleanJsonToObject:d];
                }
            }
            return dictionary;
        } else {
            return jsonObject;
        }
    }
    

    You call it by passing the NSData retrieved via NSURLConnection.

    NSArray *uableData = [utility cleanJsonToObject:data];
    

    or

    NSDictionary *uableData = [utility cleanJsonToObject:data];
    

提交回复
热议问题