简体   繁体   English

如何解析未命名数组的NSDictionary

[英]How to parse NSDictionary of unnamed arrays

Here is the NSLog result of a dictionary, dict : 这是字典dictNSLog结果:

  (
     {
         namelists = {
                        watchlist = (a, b, c, ... )
                     }
     },

     {
         namelists = {
                        watchlist = (x, y, z, ... )
                     }
     }
   )

How can I get the watchlist array? 我如何获得监视列表数组? When I tried this: 当我尝试这个:

  NSAarray *array = dict[@"nameLists"][@"watchlist"]

I get error: "unrecognized selector sent to instance". 我收到错误消息:“无法识别的选择器已发送到实例”。 I think that the unnamed array is not referred here. 我认为未命名数组不在这里引用。 How can I get the watchlist array? 我如何获得监视列表数组? Thanks in advance. 提前致谢。

You're under the impression that you're dealing with a dictionary. 您觉得自己正在处理字典。 But that's an array of dictionaries. 但这是一系列字典。 So you want: 所以你要:

NSArray *jsonObject = ... // get that main object however you want, presumably NSJSONSerialization
NSArray *watchlist = jsonObject[0][@"namelists"][@"watchlist"]

or 要么

for (NSDictionary *dict in jsonObject)
{
    NSArray *watchlist = dict[@"namelists"][@"watchlist"];

    // now do something with watchlist
}

this data structure can be coded like this 这个数据结构可以像这样编码

NSArray *arrayOfNamelists = @[@{@"namelists" : @{@"watchlist" : @[@"a",@"b",@"c"]}},
                              @{@"namelists" : @{@"watchlist" : @[@"x",@"y",@"z"]}}];

and an element in the array of strings can be accessed like this 并且可以像这样访问字符串数组中的元素

NSString *entry = [[arrayOfNamelists[1] objectForKey:@"namelists"]
                   objectForKey:@"watchlist"][2];

which in this example gives 'z' 在此示例中给出“ z”

To check this 要检查这个

NSLog(@"%@\ncount = %i",arrayOfNamelists,arrayOfNamelists.count);

for(NSDictionary *namelistDictionary in arrayOfNamelists){
    NSDictionary *watchlistDictionary = [namelistDictionary objectForKey:@"namelists"];
    NSArray *watchlistsArray = [watchlistDictionary objectForKey:@"watchlist"];
    for(NSString *watchlistEntry in watchlistsArray){
        NSLog(@"%@",watchlistEntry);
    }
};

gives

(
    {
    namelists =         {
        watchlist =             (
            a,
            b,
            c
        );
    };
},
    {
    namelists =         {
        watchlist =             (
            x,
            y,
            z
        );
    };
}

)

count = 2 计数= 2

a 一种

b b

c C

x X

y ÿ

z ž

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM