【问题标题】:IOS JSON get all values from a "JSON Dict"IOS JSON 从“JSON Dict”中获取所有值
【发布时间】:2023-03-05 05:34:01
【问题描述】:

我有这个数据结构:

{ 
  "artistlist " : [ 
                    {
                      "performer" : "Gate Zero"
                    },
                    {
                      "performer" : "nightech"
                    },
                    {
                      "performer" : "Marko Fuerstenberg"
                    },

                  ] 
   }

我用这行代码将这个结构从 NSString 读入 NSDictionary:

   JSON = [NSJSONSerialization JSONObjectWithData:
   [[chunks objectAtIndex:1]        
   dataUsingEncoding:NSUTF8StringEncoding] options:              
   NSJSONReadingMutableContainers error: &e];

with:[JSON objectForKey:@"artistlist "] 我得到了这个结构:

(
    {
    performer = "Gate Zero";
},
    {
    performer = nightech;
},
    {
    performer = "Marko Fuerstenberg";
}
)

有什么办法可以“更深入”吗?

我将如何解析结果结构?

我想获取值列表或直接访问执行者姓名。如果我在元组中有多个值,例如表演者姓名、专辑、年份,该怎么办。我将如何访问这些值?

谢谢。

【问题讨论】:

    标签: iphone objective-c ios json


    【解决方案1】:

    是的,在您拥有[JSON objectForKey:@"artistlist "] 之后,您将获得NSDictionaries 中的NSArray(有点混乱!)。

    NSArray *performersArray = [JSON objectForKey:@"artistlist"];  
    for (NSDictionary *performerDic in performersArray) {
        NSLog(@"%@", [performerDic objectForKey:@"performer"]);
    }
    

    这应该会产生每个表演者的名字。或者,您可以使用for (NSUInteger i = 0; i < [performersArray count]; i++) 并访问NSDictionary *performersDic = [performersArray objectAtIndex: i]。从那里,您可以类似地使用[performsDic objectForKey:@"performer"]

    【讨论】:

      【解决方案2】:

      像这样:

      [[[JSON objectForKey:@"artistlist "] objectAtIndex: 1] objectForKey:@"performer"]
      

      它会给你"nightech"

      {}对应NSDictionary[]对应NSArray

      【讨论】:

        【解决方案3】:

        你必须使用递归。例如,假设您只有嵌套的 NSDictionaries(易于修改以使用 NSArrays):

        - (void) getArtistFromJsonObject:(NSDictionary *)obj {
            for (NSString *key in [obj allKeys]) {
                id child = [obj objectForKey:key];
                if ([child isKindOfClass:[NSString class]]) {
                    // that's the actual string
                    // NSLog(@"Found artist: %@", child); // or do whatever needed
        
                } else if ([child isKindOfClass:[NSDictionary class]]) {
                    [self getArtistFromJsonObject:child];
                }
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-08-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多