NSJSONSerialization not creating mutable containers

前端 未结 4 1721
孤街浪徒
孤街浪徒 2021-02-07 10:05

Here\'s the code:

NSError *parseError;
NSMutableArray *listOfObjects = [NSJSONSerialization JSONObjectWithData:[@\"[]\" dataUsingEncoding:NSUTF8StringEncodin         


        
4条回答
  •  天命终不由人
    2021-02-07 10:34

    Here's my workaround for this problem:

    #import "NSJSONSerialization+MutableBugFix.h"
    
    @implementation NSJSONSerialization (NSJSONSerialization_MutableBugFix)
    
    + (id)JSONObjectWithDataFixed:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error {
        id object = [NSJSONSerialization JSONObjectWithData:data options:opt error:error];
    
        if (opt & NSJSONReadingMutableContainers) {
            return [self JSONMutableFixObject:object];
        }
    
        return object;
    }
    
    + (id)JSONMutableFixObject:(id)object {
        if ([object isKindOfClass:[NSDictionary class]]) {
            // NSJSONSerialization creates an immutable container if it's empty (boo!!)
            if ([object count] == 0) {
                object = [object mutableCopy];
            }
    
            for (NSString *key in [object allKeys]) {
                [object setObject:[self JSONMutableFixObject:[object objectForKey:key]] forKey:key];
            }
        } else if ([object isKindOfClass:[NSArray class]]) {
            // NSJSONSerialization creates an immutable container if it's empty (boo!!)
            if (![object count] == 0) {
                object = [object mutableCopy];
            }
    
            for (NSUInteger i = 0; i < [object count]; ++i) {
                [object replaceObjectAtIndex:i withObject:[self JSONMutableFixObject:[object objectAtIndex:i]]];
            }
        }
    
        return object;
    }
    
    @end
    

    So I call:

    NSDictionary *object = [NSJSONSerialization JSONObjectWithDataFixed:jsonData options:NSJSONReadingMutableContainers error:&err];
    

    Instead of the usual:

    NSDictionary *object = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
    

提交回复
热议问题