【问题标题】:How to check value null and replace it in NSDictionary如何检查值 null 并在 NSDictionary 中替换它
【发布时间】:2012-12-03 01:56:01
【问题描述】:

现在,我正在使用 NSUserDefault 和 NSDictionary,我将 NSDictionary 保存在 NSUserDefault 中,不幸的是我不能,因为返回 Json 的 NSDictionary 具有 null 值。

我需要检查 NSDictionary 是否有空值并替换。怎么样?

这是 NSDictionary,

({
  ID:11,
   name:21-12-2012,
   des:"<null>",
   url: 
     [
       {
         ID:1,
         name: "<null>"
       },
       {
         ID:2,
         name:"<null>"
       }
      ]
},
{
   ID:12,
   name:if i die young,
   des:"<null>",
   url: 
     [
       {
         ID:3,
         name: "<null>"
       },
       {
         ID:21,
         name:"<null>"
       }
      ]
})

【问题讨论】:

  • 请看我的更新,我尽力了:)
  • 我可以将 json 转换为 NSString 并替换值 null 然后 NSString 转换为 NSDictionary,我想
  • 我更新了我的代码,请看。
  • 查看我的更新,我从 nsarray 创建新的 nsmutablearray,更新值,然后用更新一个替换过时的数组
  • 我把 nslog 与 [object objectAtIndex:i] 是 NSDictionary ->NSLog(@"1-%@",[object objectAtIndex:i]);并使用 NSLog(@"2 - %@",object) -> NSArray,使用 NSDictionary 我用来设置对象但出错。 ???

标签: ios json nsdictionary


【解决方案1】:

你能检查一下这个链接吗,我想,这对你有帮助,谢谢这个链接 Replace occurrences of NSNull in nested NSDictionary

UPDATE:我稍微修改了原来的,并使用了一些从这个链接Convert NSArray to NSDictionary将nsarray转换为nsdictionary的功能,因为我对你的代码一无所知,所以我尝试让我的json字符串为尽可能接近与您的相同,这是有效的,请参见以下内容。 :)

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    tmpDict = [[NSMutableDictionary alloc] init];


    NSMutableDictionary *testDict = [[NSMutableDictionary alloc] init];
    [testDict setValue:[NSNull null] forKey:@"NullValue"];
    [testDict setValue:@"test" forKey:@"UnNull"];
    subArr = [[NSMutableArray alloc] initWithObjects:testDict, testDict, nil];

    [tmpDict setValue:[NSNull null] forKey:@"NullHere"];
    [tmpDict setValue:@"wear" forKey:@"NotNull"];
    [tmpDict setObject:subArr forKey:@"Array"];

    myArr = [[NSMutableArray alloc] initWithObjects:tmpDict, tmpDict, nil];
    NSLog(@"struct: %@", myArr);

    [self dictionaryByReplacingNullsWithStrings];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void) dictionaryByReplacingNullsWithStrings {
    const NSMutableDictionary *replaced = [NSMutableDictionary dictionaryWithDictionary: [self indexKeyedDictionaryFromArray:myArr]];
    const id nul = [NSNull null];
    const NSString *blank = @"";

    for (NSString *key in [replaced allKeys]) {
        const id object = [replaced objectForKey: key];
        if (object == nul) {
            [replaced setObject: blank forKey: key];
        }
        else if ([object isKindOfClass: [NSDictionary class]]) {
            NSLog(@"found null inside and key is %@", key);
            [replaced setObject:[self replaceNullInNested:object] forKey:key];
        }

    }
    NSLog(@"replaced: %@", replaced);
}

- (NSMutableDictionary *)replaceNullInNested:(NSDictionary *)targetDict
{
    //make it to be NSMutableDictionary in case that it is nsdictionary
    NSMutableDictionary *m = [targetDict mutableCopy];
    NSMutableDictionary *replaced = [NSMutableDictionary dictionaryWithDictionary: m];
    const id nul = [NSNull null];
    const NSString *blank = @"";

    for (NSString *key in [replaced allKeys]) {
        const id object = [replaced objectForKey: key];
        if (object == nul) {
            [replaced setObject: blank forKey: key];
        }
        else if ([object isKindOfClass: [NSArray class]]) {
            NSLog(@"found null inside and key is %@", key);
            //make it to be able to set value by create a new one
            NSMutableArray *a = [object mutableCopy];
            for (int i =0; i< [a count]; i++) {

                for (NSString *subKey in [[a objectAtIndex:i] allKeys]) {
//                    NSLog(@"key: %@", subKey);
//                    NSLog(@"value: %@", [[object objectAtIndex:i] valueForKey:subKey]);
                    if ([[object objectAtIndex:i] valueForKey:subKey] == nul) {
                        [[object objectAtIndex:i] setValue:blank forKey:subKey];
                    }
                }

            }
            //replace the updated one with old one
            [replaced setObject:a forKey:key];

        }

    }

    return replaced;
}

- (NSDictionary *) indexKeyedDictionaryFromArray:(NSArray *)array
{
    id objectInstance;
    NSUInteger indexKey = 0;

    NSMutableDictionary *mutableDictionary = [[NSMutableDictionary alloc] init];
    for (objectInstance in array)
        [mutableDictionary setObject:objectInstance forKey:[NSNumber numberWithUnsignedInt:indexKey++]];

    return (NSDictionary *)mutableDictionary;
}

从上面的代码,结果如下:

replacenullvalue[1590:11303] struct: (
        {
        Array =         (
                        {
                NullValue = "<null>";
                UnNull = test;
            },
                        {
                NullValue = "<null>";
                UnNull = test;
            }
        );
        NotNull = wear;
        NullHere = "<null>";
    },
        {
        Array =         (
                        {
                NullValue = "<null>";
                UnNull = test;
            },
                        {
                NullValue = "<null>";
                UnNull = test;
            }
        );
        NotNull = wear;
        NullHere = "<null>";
    }
)
2012-12-16 15:16:22.790 replacenullvalue[1590:11303] found null inside and key is 0
2012-12-16 15:16:22.790 replacenullvalue[1590:11303] found null inside and key is Array
2012-12-16 15:16:22.791 replacenullvalue[1590:11303] found null inside and key is 1
2012-12-16 15:16:22.791 replacenullvalue[1590:11303] found null inside and key is Array
2012-12-16 15:16:22.792 replacenullvalue[1590:11303] replaced: {
    0 =     {
        Array =         (
                        {
                NullValue = "";
                UnNull = test;
            },
                        {
                NullValue = "";
                UnNull = test;
            }
        );
        NotNull = wear;
        NullHere = "";
    };
    1 =     {
        Array =         (
                        {
                NullValue = "";
                UnNull = test;
            },
                        {
                NullValue = "";
                UnNull = test;
            }
        );
        NotNull = wear;
        NullHere = "";
    };
}

希望对你有帮助:)。

【讨论】:

  • 在这个 if ([object isKindOfClass: [NSDictionary class]]) 条件下,能否请您 nslog 并检查它是否进入这个 if 条件。
  • 错误是:[__NSCFArray dictionaryByReplacingNullsWithStrings]:无法识别的选择器发送到实例 0x9c8d3b0 并由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:'-[__NSCFArray dictionaryByReplacingNullsWithStrings]:无法识别的选择器发送到实例 0x9c8d3b0'
  • 您的字符串 json 代码工作正常,当我的 json 字符串传输时,“for (NSString *key in [replaced allKeys])”出现错误,我不知道为什么?我想你和我的两个 json 可能有问题
  • [[yourDictionary objectAtIndex:0] allKeys] 问题解决了吗?
  • 您在“for (NSString *key in [replaced allKeys]) 处说错误,那么错误是什么?(我之前的评论是我的猜测)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-12
  • 1970-01-01
  • 1970-01-01
  • 2016-02-17
  • 1970-01-01
相关资源
最近更新 更多