0

如何获取此 json。它具有动态值。下面是json。

{
 Level1: 
  {
  row1:
  {
  1: "on",
  2: "on",
  3: "on",
  4: "on",
  5: "on",
  6: "on",
  7: "on",
  8: "on",
  9: "on",
  10: "on",
  attr: {
  total: "10",
   type: "gold"
   }
   },
   row2: {
   1: "on",
   2: "on",
   3: "on",
   4: "on",
   5: "on",
  6: "on",
   7: "on",
  8: "on",
  9: "on",
  10: "on",
  attr: {
  total: "10",
  type: "gold"
  }
  }
  },
  Level3: {
 row1: {
 1: "on",
 2: "on",
 3: "on",
 4: "on",
 5: "on",
 6: "on",
 7: "on",
 8: "on",
  9: "on",
 10: "on",
 attr: {
 total: "10",
 type: "silver"
 }
 }
 }
 }

在这个数量级中,行数是动态的,里面的座位也是动态的,如何解决这个问题我不明白。请指导以上,我已经花了一天的时间。下面是我尝试过的代码。

  arrLevels = [self.mGetDataDict allKeys];          // getting all levels here in array
  NSLog(@"keys:%@", arrLevels);

  for(int i=0; i<[arrLevels count]; i++)       // trying to get rows in array 
 {
    receiveDataDict = [self.mGetDataDict valueForKey:[arrLevels objectAtIndex:i]];
    [arrRows addObject:[NSString stringWithFormat:@"%d", [receiveDataDict count]]];
    NSLog(@"data:%@", receiveDataDict);
    for(int j=0; j<[receiveDataDict count]; j++)
    {
        NSLog(@"count:%d", [receiveDataDict count]);
        dictRow = [receiveDataDict valueForKey:@"attr"];
        [arrTot addObject:[dictRow valueForKey:@"total"]];
        [arrType addObject:[dictRow valueForKey:@"type"]];
    }
 }
4

2 回答 2

4

你为什么不使用 NSJSONSerialization 类?我已经为您链接了 Apple 文档,现在您知道了一个非常有用的类的名称,您应该能够轻松找到大量可以使用的教程。

只需将您的数据提供给它,您就会得到一个 NSDictionary 对象。

当然,下一个挑战将是如何处理出现在新解析字典下的所有各种 Objective-C 对象。

一种方法是通过 keyPaths。例如:

NSString * onOrOff = [receiveDataDict valueForKeyPath: @"row1.1"];

这是一个相关的问题,其中一些答案可能会对您有所帮助

于 2013-05-20T04:18:00.200 回答
2

第 1 步:从此处下载适用于 IOS 的 JSON 框架,并将库文件添加到您的项目中

#import "JSON.h"第 2 步:在您的.h文件中导入

第 3 步:从服务器或本地获取您的 json 数据。

NSData *data = ...Your JSON Data...;
NSString *responseString = [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSUTF8StringEncoding];

// Parse it Using SBJSON
NSDictionary *dictResults = [NSDictionary dictionaryWithDictionary:[responseString JSONValue]];

// Read all Levels
for(NSString *key in [dictResults allKeys])
{
    NSLog(@"Accessing .... %@",key);
    for(NSString *rowKey in dictResults[key])
    {
        NSLog(@"%@",rowKey);
        for(NSString *valueKey in dictResults[key][rowKey])
        {
            NSLog(@"%@ -> %@",valueKey,dictResults[key][rowKey][valueKey]);
        }
        NSLog(@"--------ROW OVER------------\n");            
    }
    NSLog(@"--------------------\n");
}
于 2013-05-20T04:28:49.087 回答