Search code examples
objective-cjsonnsstringnsdatansjsonserialization

json to nsmutablearray in objective-C


We have json file (content.json).We need get data form .json file and then place into NSMutablearray. We tried like this

 NSString* path  = [[NSBundle mainBundle] pathForResource:@"content" ofType:@"json"];

NSString* jsonString = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];

 NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];

   id allKeys = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONWritingPrettyPrinted error:&jsonError];
NSLog(@"Key ***  %@",allKeys);

    for (int i=0; i<[allKeys count]; i++) {
        NSDictionary *arrayResult = [allKeys objectAtIndex:i];
        NSLog(@"name=%@",[arrayResult objectForKey:@"Description"]);

    }

allKeys Value is null

JsonString is


    [
          {
          "ID": “2”,
          "MessageType": "0",
          "Description": "Promotions”,
          "ExpiryDateTime": "2015-07-10 12:00:00", 
          "Html": "<div class=\"ad_box\"><img class=\"banner\" src=\"jewellery.jpg\"\/><h3>"Hot" Items<ul \/><\/div>"
          },
          {
          "ID": "4",
          "MessageType": "1",
          "Description": "Offers”,
          "ExpiryDateTime": "2015-07-09 2:00:00", 
          "Html": "<div class=\"ad_box\"><img class=\"banner\" src=\"Williams-Petersan.jpg\"\/><h3>"Hot" Items - 2<ul \/><\/div>"
           }
           {
           "ID": “6”,
          "MessageType": “2”,
          "Description": "Invitations”,
          "ExpiryDateTime": "2015-07-09 3:00:00", 
          "Html": "<div class=\"ad_box\"><img class=\"banner\" src=\"Puma.jpg\"\/><h3>"Hot" Items - 2<ul \/><\/div>"
           }
]

We need Description data placed into ArrayResult

Please guide to us


Solution

  • your json is invalid - notice the unicode quotes around ID 2 or 6 - ID 4 is fine -- there multiple errors more which can easily be fixed :) e.g. by using some online son validator website / a supported editor

    the code itself looks okay

    BUT

    it wont be a mutable array ;) it will be immutable. If you want Mutability, pass NSJSONReadingMutableContainers to the JSON