user688518
user688518

Reputation: 461

Converting a JSON file to NSMutableDictionary in Objective C?

I have a json file that looks like this:

{
    "data": 
    {
        "level": [
            {
            //bunch of stuff
            }
            ]
    }
}

Now I want to convert that into a array of levels that I can access. If I take away the {"data: part, then I can use this:

NSData *allLevelsData = [[NSData alloc] initWithContentsOfFile:fileLoc];
NSError *error = nil;
NSMutableDictionary *allLevels = [NSJSONSerialization JSONObjectWithData:allLevelsData options:kNilOptions error:&error];
if(!error){
        NSMutableArray *level = allLevels[@"level"];
        for (NSMutableDictionary *aLevel in level){
            //do stuff with the level...

But I have to have the {"data: as part of the file, and I can't figure out how to get a NSData object out of the existing NSData object. Any ideas?

Upvotes: 0

Views: 297

Answers (2)

DanielG
DanielG

Reputation: 2377

Don't you need to pull the level NSArray out of the data NSDictionary first?

NSData *allLevelsData = [[NSData alloc] initWithContentsOfFile:fileLoc];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:allLevelsData options:kNilOptions error:&error];
if(!error){
    NSArray *levels = dataDictionary[@"data"][@"level"];
    for (NSDictionary *aLevel in levels){
        //do stuff with the level...

Upvotes: 1

Brad Brighton
Brad Brighton

Reputation: 2184

  1. You won't get mutable objects back by default and declaring the variables as mutable doesn't make them so. Take a mutableCopy of the result instead (assuming you really do need mutability).
  2. Why are you trying to prune ahead of time? If you decode the original JSON, you'll be able to extract the level array from the data dict in the decoded dict.

It's not clear what else you're trying to accomplish or why you are going the path you ask about. Note, this doesn't necessarily mean your path is wrong, just that without a clearer indication of what goal you're really trying to accomplish or what you've actually tried (and errored/failed, along with how it failed), you're likely only to get vague/general answers like this.

Upvotes: 0

Related Questions