如何获取这个json

时间:2013-05-20 04:14:09

标签: objective-c json

如何获取这个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"]];
    }
 }

2 个答案:

答案 0 :(得分:4)

Why are you not using the NSJSONSerialization class?我已经为您链接了Apple文档,现在您知道非常有用的类的名称,您应该能够轻松找到大量可以使用的教程。

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

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

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

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

Here is a related question with some answers that may help you out

答案 1 :(得分:2)

步骤1:从here下载IOS的JSON框架,并将库文件添加到项目中

第2步:在#import "JSON.h"文件中导入.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");
}