BostonMacOSX BostonMacOSX - 2 months ago 7
JSON Question

How should I format incoming JSON for UITableView with sections

I'm writing an iOS app(my first one) and also am designing a feed from a database for events. The events are divided into logical groupings by topic. I want the end game with swiftyJSON to be a table with sections and section headers. A possible JSON will look like but I'm willing to change it completely:

{
"events":[
{"school events":
[
{"title":"event1school","start_date":"01/01/01"},
{"title":"eventschool2","start_date":01/02/01"}
]
},
{"town events":
[
{"title":"event1school","start_date":"01/01/01"},
{"title":"eventschool2","start_date":01/02/01"}
]
}
]
}


what I'm trying to accomplish is deliver a dictionary where they keys are the section headers and the rows are the array of infomration below the keys. I'm just new to iOS and have created a table from a JSON feed but haven't designed one from scratch.

Any advice appreciated.

I've gotten closer.

self.swiftyJsonVar = JSON(jJson)

for(key,object) in self.swiftyJsonVar["events"]{
print(key)
print(object)
}


which prints

0
{
"SCHOOLS" : [

]
}


It loops fine as well but I'm not sure how to get to the key and then the values after...I'm close...;)

Answer

I have taken your JSON in a local file and parsed in following way. You can follow the same way to parse it. I have taken a demo model object to keep the data

Swift Version :

My Model object looks like

import UIKit

class ReceipeBO: NSObject {


var headerValue : NSString!
var arrEvents   : NSArray!

init(headerValue:NSString, arrEvents:NSArray) {
    self.headerValue = headerValue;
    self.arrEvents = arrEvents;
}

}

So from the model object you can see, I am keeping the key in headerValue property and the event array of dictionaries in arrEvents

Here is the method where I am fetching from JSON response

func getLocalJsonData()
{
    let filePath = NSBundle.mainBundle().pathForResource("test", ofType: "json");

    let data = NSData.init(contentsOfFile: filePath!);

    var json : NSArray!
    var jsonTemp : NSDictionary = NSDictionary()

    do{
        jsonTemp = try  NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableLeaves) as! NSDictionary;
    }catch{

    }

    print("jsonTemp \(jsonTemp)");

    json = jsonTemp["events"] as! NSArray;

    print("json \(json)");

    let arrEvents = NSMutableArray();

    for dictTemp in json
    {
        let key = dictTemp.allKeys.first as! String;
        let arrValue = dictTemp[key] as! NSArray;

        let receipe = ReceipeBO(headerValue: key, arrEvents: arrValue);
        arrEvents.addObject(receipe);
    }

    print("evnts : \(arrEvents)");

}

Now come to Objective C version :

My Model object looks like

#import <Foundation/Foundation.h>

@interface ReceipeBO : NSObject

@property (nonatomic, strong) NSString *headerValue;
@property (nonatomic, strong) NSMutableArray *arrEvents;


@end

Now in the similar manner explained above the JSON fetching function is as below

- (void)getLocalJsonData
{
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"json"];
    NSData *jsonData = [[NSData alloc] initWithContentsOfFile:filePath];

    NSDictionary *jsonTemp = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:nil];

    NSArray *json = jsonTemp[@"events"];

    NSMutableArray *arrEvents = [NSMutableArray array];

    for (NSDictionary *dictTemp in json) {
        ReceipeBO *receipe = [[ReceipeBO alloc] init];

        NSString *key = [dictTemp.allKeys firstObject];
        receipe.headerValue = key;
        receipe.arrEvents = dictTemp[key];

        [arrEvents addObject:receipe];
    }

    //Access or fetching part

    for (ReceipeBO *objReceipe in arrEvents) {
        NSLog(@"Section header : %@", objReceipe.headerValue);

        for (NSDictionary *dictEvent in objReceipe.arrEvents) {
            NSLog(@"Event title %@ : Event start date %@", dictEvent[@"title"], dictEvent[@"start_date"]);
        }
    }
}

Output :

 Section header : school events Event title event1school : Event start
 date 01/01/01 Event title eventschool2 : Event start date 01/02/01
 Section header : town events Event title event1school : Event start
 date 01/01/01 Event title eventschool2 : Event start date 01/02/01

Hope it helps.

Happy coding ...

Comments