0

I have problem reaching the title and description string in my JSON. I can reach the tab name and the category name, but I don't know how to reach the item description and title.

Here's my 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"
                 }
            ]
        }
    ]

}

Here's my code for parsing:

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

    }

}

How can I reach each title and description and push them into my Category model object array called items?

4

1 回答 1

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
    }

}
于 2013-04-24T18:00:51.367 回答