为NSDictionary中的内部键获取键的对象的最佳方式



也许这个问题的标题不是很清楚。我有如下json:

// {
//    "aps": {
//        "alert": {
//            "title":"nice title",
//            "body":"A nice body. $savings"
//        },
//        "content-available":"1"   //This flag set enables background processing
//    },
//    "blabla":"1",
//    "spend_amount":"$cash",
//    "save_amount":"$savings"
// }           

要获得标题内的信息,我需要做任何一个:

 NSString * _message = [[[userInfo objectForKey:@"aps"] objectForKey:@"alert"] objectForKey:@"body"];

或者定义三个二变量

id payload = [userInfo objectForKey:@"aps"];
id alert = [payload objectForKey:@"alert"];
NSString * _actionTitle = [alert objectForKey:@"title"];

有更好的方法吗?

尝试使用以下一行代码来获取嵌套字典键值:

[userInfo valueForKeyPath:@"aps.alert.title"];

我只是创建示例和测试代码:

    NSMutableDictionary *d =[[NSMutableDictionary alloc]init];
    [d setValue:@"A nice body. $savings" forKey:@"body"];
    [d setValue:@"nice title" forKey:@"title"];

    NSMutableDictionary *b =[[NSMutableDictionary alloc]init];
    [b setValue:d forKey:@"alert"];
    NSMutableDictionary *e =[[NSMutableDictionary alloc]init];
    [e setValue:@"1" forKey:@"content-available"];
    [e setValue:b forKey:@"aps"];
    NSLog(@"Dictioarn = %@",e);
    NSLog(@"Dictioarn = %@",[e valueForKeyPath:@"aps.alert.title"]);

输出是:

Dictioarn = nice title

使用此代码,

在body关键字中更改objectForKey而不是valueForKey

NSString * _message = [[[userInfo objectForKey:@"aps"] objectForKey:@"alert"] valueForKey:@"body"];

希望它对有帮助

最新更新