how to parse json string and store the object in an array in iphone - iphone

I am getting data from server it gives in response a NSString which hase json data i want that json data to be store in an array how to do this
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(data);
NSData* data=[dataString dataUsingEncoding:NSUTF8StringEncoding];
[self performSelectorOnMainThread:#selector(fetchedData:)
withObject:data waitUntilDone:YES];
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
NSArray* latestLoans = [json objectForKey:#"loans"]; //2
NSLog(#"loans: %#", latestLoans); //3
}
here is the log of data which return from server
[{"CodeValue":"90658","CodeDescription":"flu shot","IsActive":"1","CodeType":"CPT","CodeID":"6","UpdateDateTime":"2012-04-02 02:09:46"}]

NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSArray *dataArr=[data JSONValue];
for (int i=0; i<[dataArr count]; i++) {
NSDictionary *dict=[dataArr objectAtIndex:i];
NSString *codeV=[dict valueForKey:#"CodeValue"];
NSString *codeD=[dict valueForKey:#"CodeDescription"];
NSString *active=[dict valueForKey:#"IsActive"];
NSString *codeT=[dict valueForKey:#"CodeType"];
NSString *codeId=[dict valueForKey:#"CodeID"];
NSString *updatedTime=[dict valueForKey:#"UpdateDateTime"];
NSLog([dict description],nil);
}
NSLog(#"%#", json_string);
//May this will help you out.
Do include the JSon library classes to your project.
I am doing in this way to insert in an array but it return o object
NSDictionary *dict=[dataArr objectAtIndex:i];
SearchCode *theObject =[[SearchCode alloc] init];
theObject.codeValue=[dict valueForKey:#"CodeValue"];
theObject.codeDescription=[dict valueForKey:#"CodeDescription"];
theObject.codeType=[dict valueForKey:#"CodeType"];
theObject.codeID=[dict valueForKey:#"CodeID"];
theObject.UpdateDateTime=[dict valueForKey:#"UpdateDateTime"];
NSLog(codeType);
[cptArray addObject:theObject];
[theObject release];
theObject=nil;
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [cptArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.selectionStyle=UITableViewCellSelectionStyleGray;
cell.accessoryType = UITableViewCellAccessoryNone;
}
SearchCode *theObject =[cptArray objectAtIndex:indexPath.row];
cell.textLabel.text=theObject.codeValue; //& so on you can access any value from "theObject" here
}

If you want a more packaged solution check out: https://github.com/stig/json-framework
Its a awesome framework, to parse JSON you can just type
[string_here JSONValue];

Related

How to display array of JSON values in custom tableView cells

I want to pass values inside for(NSDictionary *jsonDictionary in myJsonArray) which I get in NSLog to [array addObject:[[SaveList alloc] initWithEmail:email withPhone:phone withDate:date withName:name]];
Code is here
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSError *error = nil;
NSURL *url = [NSURL URLWithString:#" http:// Some url "];
NSString *json = [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding error:&error];
NSLog(#"\n\n JSON : %#, \n Error: %#", json, error);
if(!error)
{
NSData *jsonData = [json dataUsingEncoding:NSASCIIStringEncoding];
NSArray *myJsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
// NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
for(NSDictionary *jsonDictionary in myJsonArray)
{
NSLog(#"JSON Dictionary = %#", jsonDictionary);
NSString *name = jsonDictionary[#"Name"];
NSString *date = jsonDictionary[#"Date"];
NSString *email = jsonDictionary[#"Email"];
NSString *phone = jsonDictionary[#"Phone"];
NSLog(#"Name = %#", name);
NSLog(#"Date = %#", date);
NSLog(#"Email = %#", email);
NSLog(#"Phone = %#", phone);
}
}
});
//Table implementation
array = [[NSMutableArray alloc]init];
//**Get email, phone, date, name here**
[array addObject:[[SaveList alloc] initWithEmail:email withPhone:phone withDate:date withName:name]];
self.tableView.dataSource = self;
self.tableView.delegate = self;
Why don't you add the objects as you receive them? Since this block of code will be executed asynchronously you could prepare your array, set your tableview and then execute the block where you fill your array and refresh the tableview.
Something like this:
// Prepare your array
array = [NSMutableArray arrayWithCapacity:0];
// Set your tableview's datasource & delegate
self.tableView.dataSource = self;
self.tableView.delegate = self;
// Fetch data asynchronously
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSError *error = nil;
NSURL *url = [NSURL URLWithString:#" http:// Some url "];
NSString *json = [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding error:&error];
NSLog(#"\n\n JSON : %#, \n Error: %#", json, error);
if(!error)
{
NSData *jsonData = [json dataUsingEncoding:NSASCIIStringEncoding];
NSArray *myJsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
NSMutableArray *tmp = [NSMutableArray arrayWithCapacity:myJsonArray.count];
for(NSDictionary *jsonDictionary in myJsonArray)
{
NSString *name = jsonDictionary[#"Name"];
NSString *date = jsonDictionary[#"Date"];
NSString *email = jsonDictionary[#"Email"];
NSString *phone = jsonDictionary[#"Phone"];
//**Get email, phone, date, name here**
[tmp addObject:[[SaveList alloc] initWithEmail:email
withPhone:phone
withDate:date
withName:name]];
}
// Reload your tableview
dispatch_sync(dispatch_get_main_queue(), ^{
array = tmp; // Or add them to your datasource array, whatever suits you...
[self.tableView reloadData];
});
}
});
set number of rows
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
[array count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
SavedList *savedList = [array objectAtIndex:indexPath.row];
cell.text = savedList.name;
}
return cell;
}
I hope it will be helpful.
// U need to reload table view data whenever you add new object in it. It does work like a thread.
dispatch_sync(dispatch_get_main_queue(), ^{
array = myJsonArray;
[self.tableView reloadData];

ios - How to load data from JSON url in UITableView?

I'm new to iPhone development,I'm trying to bind data from JSON Url in UITableview, but I'm getting an error in the below code.
- (void)viewDidLoad
{
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://80f237c226fa45aaa09a5f5c82339d46.cloudapp.net/DownloadService.svc/Courses"]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
statuses = [parser objectWithString:json_string error:nil];
[self.dropdownTblView reloadData];
for (NSDictionary *status in statuses)
{
_altTitle = [status valueForKey:#"Title"];
NSLog(#"Title %#",_altTitle);
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(#"%d",[statuses count]);
return [statuses count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
return cell;
//Here I'm getting an error
id obj = [statuses objectAtIndex:indexPath.row];
NSString *name = [obj valueForKey:#"Title"];
cell.textLabel.text =name;
return cell;
}
This is my JSON
[
{
"Id": 1,
"Title": "Tamil to English",
"AltTitle": "த|மி|ழ்| |மூ|ல|ம்| |ஆ|ங்|கி|ல|ம்",
"Description": "Learn English through Tamil",
"Code": 1,
"Version": "1.0",
"SourceLanguageIndicator": "அ",
"TargetLanguageIndicator": "A",
"SourceLanguageCode": "ta",
"TargetLanguageCode": "en",
"Updated": "2013-02-21T03:33:19.6601651+00:00"
}
]
Any ideas? Thanks in advance.
You're returning the cell twice in the same scope, try to delete the first return cell;, also you're calling reloadData on the table just before the for loop; in this case probably the dataSource of the table is still empty, so call reloadData just after the for loop.
EDIT:
It's strange what is happening, the objectFromString must return a NSArray or a NSDictionary but it seems that is pointing to an NSSet. I can suggest 2 things in addition:
It seems that you're not usig ARC since you're calling autorelease on the UITableViewCell. In this case you're leaking parser and json_string in the viewDidLoad, so release them.
Make sure to call [super viewDidLoad]; (you're not doing this in your code).
Maybe because you set the type of obj as id. It is too generic and may not know how to respond to valueForKey. Have you tried declaring obj as an NSDictionary * instead? Like the code below:
NSDictionary *obj = [statuses objectAtIndex:indexPath.row];
NSString *name = [obj valueForKey:#"Title"];
Use the Below code in your ViewDidload and Run the Project , it will work.
Note :You're returning the cell twice, try to delete the first return
cell;
- (void)viewDidLoad
{
[super viewDidLoad];
statuses=[[NSMutableArray alloc]init];
NSURL *myURL = [NSURL URLWithString:#"http://80f237c226fa45aaa09a5f5c82339d46.cloudapp.net/DownloadService.svc/Courses"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSLog(#"Finished with status code: %i", [(NSHTTPURLResponse *)response statusCode]);
id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(#"jsonObject=%#",jsonObject);
statuses=[jsonObject mutableCopy];
[self.coursetable reloadData];
}];
NSLog(#"myURL=%#",myURL);
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(#"%d",[statuses count]);
return [statuses count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
}
id obj = [statuses objectAtIndex:indexPath.row];
cell.textLabel.text =[obj valueForKey:#"Title"];
return cell;
}
Yes I was thinking right, statuses is not NSArray, it is NSSet so if you call objectAtIndex on NSSet it will crash.To get array convert NSSet into NSArray.
NSArray *array =[statuses allObjects];
- (void)viewDidLoad
{
NSString *dictStr=#"{\"Id\": 1,\"Title\": \"Tamil to English\",\"AltTitle\": \"த|மி|ழ்| |மூ|ல|ம்| |ஆ|ங்|கி|ல|ம்\",\"Description\": \"Learn English through Tamil\",\"Code\": 1,\"Version\": \"1.0\",\"SourceLanguageIndicator\": \"அ\",\"TargetLanguageIndicator\": \"A\",\"SourceLanguageCode\": \"ta\",\"TargetLanguageCode\": \"en\",\"Updated\": \"2013-02-21T03:33:19.6601651+00:00\"}";
NSDictionary *rootDict =[NSJSONSerialization JSONObjectWithData: [dictStr dataUsingEncoding:NSUTF8StringEncoding]
options: NSJSONReadingMutableContainers
error: nil];
NSArray *keys=[[rootDict allKeys] sortedArrayUsingSelector:#selector(compare:)];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [keys count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier=#"cellIdentifier";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell==nil) {
cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
cell.textLabel.text=[rootDict valueForKey:[keys objectAtIndex:indexPath.row]];
return cell;
}
remember rootDict and keys will be declared as global.

How to parse this json in uitableview? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I am new in iOS. I wanna parse following json in my UITableView, but I don't know how to do that. I know json parsing using NSURL, but in this direct json parsing I am facing problems .please help..
here it is:
NSString *url = #"{\"LinkResult\":{\"0\":{\"Name\":\"Veeva - Devon1\",\"ButtonDisplay\":\"Veeva\",\"PasswordSaving\":\"Yes\",\"Status\":\"Success\",\"Message\":\"No Error\", \"Identifiers\": {\"Identifier1Name\": \"Identifier1value\",\"Identifier2Name\": \"Identifier2value\",\"Identifier3Name\": \"Identifier3value\"},}}}";
please tell me next steps...
This is the structure of your JSON
{
"LinkResult": {
"0": {
"Name": "Veeva - Devon1",
"ButtonDisplay": "Veeva",
"PasswordSaving": "Yes",
"Status": "Success",
"Message": "No Error",
"Identifiers": {
"Identifier1Name": "Identifier1value",
"Identifier2Name": "Identifier2value",
"Identifier3Name": "Identifier3value"
}
}
}
}
Create a json file using any online generators and add it in your project. Have a property for keeping the dataSource.
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *filePath = [[NSBundle mainBundle]pathForResource:#"Data"
ofType:#"json"];
NSData *data = [[NSData alloc]initWithContentsOfFile:filePath];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data
options:0
error:nil];
//A dictionary which will contain info all users
self.users = dict[#"LinkResult"];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [[self.users allKeys] count];;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
NSArray *sortedKeys = [[self.users allKeys]sortedArrayUsingSelector:#selector(compare:)];
NSString *key = sortedKeys[indexPath.row];
NSDictionary *user = self.users[key];
cell.textLabel.text = user[#"Name"];
cell.detailTextLabel.text = user[#"Status"];
return cell;
}
Source Code
You'd want to use the NSJSONSerialization class for this, something like:
NSData *json = [url dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
NSDictionary *identifiers = [dataDictionary objectForKey:#"Identifiers"];
// Do stuff with the data
Hope that makes sense. You can pull elements from the JSON string by using:
[dataDictionary objectForKey:#"ElementName"];
to parse you could use nsdictionary like this...
NSData *json = [url dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
NSDictionary *identifiers = [dataDictionary objectForKey:#"Your key"];
and to show it in tableview you could use
arr = [[JSONObject objectForKey:#“results”] objectForKey:#“Your key”];
// and set cell text label as -
cell.textLabel.text =[[arr objectAtIndex:indexPath.row] objectForKey:#"Your key"];
You need to convert your json string to NSDictionary object in order to used in tableView,below code will convert it to NSDictionary object and then you can set values accordingly by using its key value.
- (void)viewDidLoad
{
NSString *jsonString = #"{\"LinkResult\":{\"0\":{\"Name\":\"Veeva - Devon1\",\"ButtonDisplay\":\"Veeva\",\"PasswordSaving\":\"Yes\",\"Status\":\"Success\",\"Message\":\"No Error\", \"Identifiers\": {\"Identifier1Name\": \"Identifier1value\",\"Identifier2Name\": \"Identifier2value\",\"Identifier3Name\": \"Identifier3value\"},}}}";
NSData *jsondata=[jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsondata options:0 error:nil];
displaydata=[[dataDictionary valueForKey:#"LinkResult"] valueForKey:#"0"];
NSMutableArray *mutableKeys=[[NSMutableArray alloc] initWithArray:[displaydata allKeys]];
[mutableKeys removeObject:#"Identifiers"];
keys=[[NSArray alloc] initWithArray:mutableKeys];
NSLog(#"JSON DIct: %#", displaydata);
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [keys count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier=#"cellIdentifier";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell==nil) {
cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
cell.textLabel.text = [displaydata valueForKey:[keys objectAtIndex:indexPath.row]];
return cell;
}
NSString *url = #"{\"LinkResult\":{\"0\":{\"Name\":\"Veeva - Devon1\",\"ButtonDisplay\":\"Veeva\",\"PasswordSaving\":\"Yes\",\"Status\":\"Success\",\"Message\":\"No Error\", \"Identifiers\": {\"Identifier1Name\": \"Identifier1value\",\"Identifier2Name\": \"Identifier2value\",\"Identifier3Name\": \"Identifier3value\"},}}}";
NSData* jsonData = [url dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
NSLog(#"json is %#", json);
NSDictionary *LinkResult = [json valueForKey:#"LinkResult"];
NSLog(#"LinkResult is %#", LinkResult);
for (id key in [LinkResult allKeys]) {
NSLog(#"Value for 0 index is %#", [LinkResult valueForKey:key]);
NSLog(#"ButtonDisplay is %#", [[LinkResult valueForKey:key] valueForKey:#"ButtonDisplay"]);
NSLog(#"Message is %#", [[LinkResult valueForKey:key] valueForKey:#"Message"]);
NSLog(#"Name is %#", [[LinkResult valueForKey:key] valueForKey:#"Name"]);
NSLog(#"PasswordSaving is %#", [[LinkResult valueForKey:key] valueForKey:#"PasswordSaving"]);
NSLog(#"Status is %#", [[LinkResult valueForKey:key] valueForKey:#"Status"]);
}
Here it is friend
NSString *url = #"{\"LinkResult\":{\"0\":{\"Name\":\"Veeva - Devon1\",\"ButtonDisplay\":\"Veeva\",\"PasswordSaving\":\"Yes\",\"Status\":\"Success\",\"Message\":\"No Error\", \"Identifiers\": {\"Identifier1Name\": \"Identifier1value\",\"Identifier2Name\": \"Identifier2value\",\"Identifier3Name\": \"Identifier3value\"},}}}";
NSArray *arrComponents = [url componentsSeparatedByString:#","];
NSMutableArray *arrmFilter = [[NSMutableArray alloc] init];
for(int i = 0; i < [arrComponents count] ;i++)
{
NSString *str = [arrComponents objectAtIndex:i];
//str = [str stringByReplacingOccurrencesOfString:#":" withString:#""];
str = [str stringByReplacingOccurrencesOfString:#"\"" withString:#""];
str = [str stringByReplacingOccurrencesOfString:#"{" withString:#""];
str = [str stringByReplacingOccurrencesOfString:#"}" withString:#""];
str = [str stringByReplacingOccurrencesOfString:#"0" withString:#""];
[arrmFilter addObject:str];
}
NSLog(#"Filtered array = %#", arrmFilter);
You Will have to do Some changes in `stringByReplacingOccurencesOfString
But this vill extract JSON....
Hope this helps..

displaying JSON data in Tableview in iphone

below is the JSON i want to parse it in such a way that for e.g date 1st should all events in that section of table and 2nd date should show all related events in another section
I am parsing using below code but i am not getting required sequence
SBJsonParser *parser= [[SBJsonParser alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.krsconnect.no/community/api.html?method=bareListEventsByCategory&appid=620&category-selected=350&counties-selected=Vest-Agder,Aust-Agder"]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSDictionary *object = [parser objectWithString:json_string error:nil];
NSArray *results = [parser objectWithString:json_string error:nil];
appDelegate.books1 = [[NSMutableArray alloc] init];
appDelegate.dates =[[NSMutableArray alloc]init];
for (int j=0;j<10; j++) {
NSDictionary *dictOne = [results objectAtIndex:j];
NSLog(#"%# - %#", [dictOne objectForKey:#"date"]);
Date *aDate = [[Date alloc] initWithDictionary:[results objectAtIndex:j]];
[appDelegate.dates addObject:aDate];
[aDate release];
}
for (int i=0; i<10; i++) {
NSDictionary *dictOne = [results objectAtIndex:i];
NSArray *activitiesArray = [dictOne objectForKey:#"events"];
NSDictionary *dictTwo = [activitiesArray objectAtIndex:i];
NSDictionary *eventDict=[dictTwo objectForKey:#"event"];
// NSLog(#"%# - %#", [dictOne objectForKey:#"date"]);
// NSLog(#"%# - %#", [dictTwo objectForKey:#"affectedDate"]);
// NSLog(#"%# - %#", [eventDict objectForKey:#"location"]);
NSInteger*date=[dictOne objectForKey:#"date"];
NSInteger*affectedDate=[dictTwo objectForKey:#"affectedDate"];
NSString*appId =[eventDict objectForKey:#"appId"];
NSString*eventId=[eventDict objectForKey:#"eventId"];
NSString*location=[eventDict objectForKey:#"location"];
NSString*municipality=[eventDict objectForKey:#"municipality"];
NSString*title=[eventDict objectForKey:#"title"];
Book1 *aBook=[[Book1 alloc] initWithDate:date affectedDate:affectedDate location:location municipality:municipality title:title];
[appDelegate.books1 addObject:aBook];
int count=[appDelegate.books1 count];
}
the json format is given below
http://www.krsconnect.no/community/api.html?method=bareListEventsByCategory&appid=620&category-selected=350&counties-selected=Vest-Agder,Aust-Agder
You need to aggregate your data in some different way.
Here is how I'd do that:
...
// why do you parse your json string two times?
//NSDictionary *object = [parser objectWithString:json_string error:nil];
NSArray *results = [parser objectWithString:json_string error:nil];
// You have memory leak here. I assume that books1 and dates are both properties with "retain" flag set.
//appDelegate.books1 = [[NSMutableArray alloc] init];
//appDelegate.dates =[[NSMutableArray alloc]init];
NSMutableArray *data = [NSMutableArray array]
self.data = data;
// check that what we've parsed is NSArray
if (results && [results isKindOfClass:[NSArray class]]) {
for (NSDictionary *sectionDict in results) {
if ([sectionDict isKindOfClass:[NSDictionary class]]) {
NSString *sectionTitle = [[sectionDict objectForKey:#"date"] description];
NSArray *events = [sectionDict objectForKey:#"events"];
if (date && events && [events isKindOfClass:[NSArray class]]) {
NSMutableArray *rows = [NSMutableArray arrayWithCapacity:[events count]];
for (NSDictionary *eventDict in events) {
if ([eventDict isKindOfClass:[NSDictionary class]]) {
[rows addObject:#"testRow"];
}
}
[data addObject:[NSDictionary dictionaryWithObjectsAndKeys: sectionTitle, #"section", rows, #"rows", nil]];
}
}
}
}
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tblView {
return [data count];
}
- (NSInteger) tableView:(UITableView *)tblView numberOfRowsInSection:(NSInteger)section {
return [[[data objectAtIndex:section] objectForKey:#"rows"] count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return [[data objectAtIndex:section] objectForKey:#"section"];
}
- (UITableViewCell *) tableView:(UITableView *)tblView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellID = #"DefaultCell";
UITableViewCell *cell = (UITableViewCell *)[tblView dequeueReusableCellWithIdentifier:cellID];
if ( cell == nil ) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID] autorelease];
}
cell.textLabel.text = [[[data objectAtIndex:indexPath.section] objectForKey:#"rows"] objectAtIndex:indexPath.row];
return cell;
}

Json Parser output display in tableview

I am trying to parse using JSON Parser and the result which i get i have to put it into table view. I've passed a constant key value and a string .
Is there parsing steps wrong? or missed.
I have included the code for the JSON parser.
Thanks in advance.
SBJSON *parser = [[SBJSON alloc] init];
NSString *urlString =[NSString stringWithFormat:#"http://api.shopwiki.com/api/search?key=%#&q=%#",apiKey, string];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL: url];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSMutableArray *statuses = [[NSMutableArray alloc]init];
statuses = [parser objectWithString:json_string error:nil];
NSLog(#"Array Contents: %#", statuses);
NSMutableArray *statuses0 = [[NSMutableArray alloc]init];
statuses0 = [statuses valueForKey:#"offers"];
NSLog(#"Array Contents: %#", statuses0);
//For Title
NSMutableArray *statuses1 = [[NSMutableArray alloc]init];
statuses1 = [[[statuses valueForKey:#"offers"] valueForKey:#"offer"]valueForKey:#"title"];
NSLog(#"Array Contents 4 Title: %#", statuses1);
Here in statuses1 array i get 20 objects which are all titles, now i just want to display that titles into tableview:-
snippet code for tableview:-
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSLog(#"status count:%d",[statuses1 count]);
return [statuses1 count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(#"Inside Tableview");
int counter=indexPath.row;
NSString *CellIdentifier = [NSString stringWithFormat:#"%d",counter];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.selectionStyle=UITableViewCellSelectionStyleNone;
}
NSLog(#"Inside Tableview 1");
cell.textLabel.text=[statuses1 objectAtIndex:indexPath.row];
NSLog(#"Inside Tableview 2");
return cell;
}
I get Bad excess exception whten it hits on :-
cell.textLabel.text=[statuses1 objectAtIndex:indexPath.row];
Please give me the solution
thanks in advance:-
If you're getting EXC_BAD_ACCESS on that line, it's probably because statuses1 has been released by the time cellForRowAtIndexPath is called. What block of code is this line in?
NSMutableArray *statuses1 = [[NSMutableArray alloc]init];
The statuses1 variable above is local to whatever scope you've declared it in. Do you then assign it to your UITableViewController.statuses1 ivar? Is that a retained property?