【问题标题】:Reaching items in JSON.以 JSON 格式获取项目。
【发布时间】:2013-04-25 02:00:51
【问题描述】:

我在获取 JSON 中的标题和描述字符串时遇到问题。 我可以访问选项卡名称和类别名称,但我不知道如何访问项目描述和标题。

这是我的 JSON:

{
    "tab1": 
    [
        {
            "category1Tab1":
            [
                {   
                    "title":"film1", 
                    "description": "desc1"
                },
                { 
                    "title": "film2",
                    "description": "desc2"
                }
            ],
             "category2Tab1":
             [
                  {
                      "title": "tv",
                      "description": "desc1"
                  },
                  {
                      "title": "tv2",
                      "description": "desc2"
                  }
              ]
        }
    ],
    "tab2": 
    [
        {
            "category1Tab2":
            [ 
                {   
                    "title":"item1", 
                    "description": "desc1"
                },
                { 
                    "title": "item2",
                    "description": "desc2"
                 }
            ]
        }
    ]

}

这是我的解析代码:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"json"];
NSString *contents = [NSString stringWithContentsOfFile: filePath  encoding: NSUTF8StringEncoding error: nil];
SBJsonParser *jsonParser = [[SBJsonParser alloc] init];


NSMutableDictionary *json = [jsonParser objectWithString: contents];
jsonParser = nil;

for (NSString *tab in json)
{
    Tab *tabObj = [[Tab alloc] init];
    tabObj.title = tab;

    NSDictionary *categoryDict = [[json valueForKey: tabObj.title] objectAtIndex: 0];
    for (NSString *key in categoryDict)
    {

        Category *catObj = [[Category alloc] init];
        catObj.name = key;

        //Code for the items

    }

}

如何获取每个标题和描述并将它们推送到名为 items 的 Category 模型对象数组中?

【问题讨论】:

  • 剥洋葱皮。 {} 是一个“对象”(字典)。 [] 是一个数组。一次走一层。 NSLog 你得到什么以确保你理解它。 (请注意,NSLog 使用() 代替{}= 代替:。)
  • 啊,NSLog 的 = 和 () 让我很困惑!谢谢

标签: objective-c json


【解决方案1】:
for (NSString *key in categoryDict)
{

    Category *catObj = [[Category alloc] init];
    catObj.name = key;

    NSArray *items = [categoryDict objectForKey:key];
    // you should add error checking to make sure this is actually an NSArray

    for (NSDictionary *dict in items) {
        NSString *theTitle = [dict objectForKey:@"title"];
        NSString *theDescription = [dict objectForKey:@"description"];

        // do something with theTitle and theDescription
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多