Parsing Value Showing Error in iphone - iphone

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];
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]];
}
}
}
}
Now when i use this data in display on table view it show testRow on all cell but i want location on cell text and municipality in detailtext which come from JSON so how to do this

change
[rows addObject:#"testRow"];
to
[rows addObject:[eventDict objectForKey:#"location"]];
I'd suggest that you create a Event class with necessary attributes, such as location, municipality. Then you can do:
Event *event = [[Event alloc] init];
event.location = [eventDict objectForKey:#"location"];
event.municipality = [eventDict objectForKey:#"municipality"]]
[rows addObject:event];
[event release];
Then you can use the rows in your controller.

Related

Import csv file into SQLite

I have a database in SQLite, and a table named xyz which is empty. I want to import data from a csv file into that table.
Now, when I try to import csv file, it is asking me to import it into the main table, but I want to import the data into my xyz table.
How can I do that?
You can do as this way,
First you need to add your csv file in bundle.
Then you can call this method where you want to add data in database from csv
-(void)loadCSVData{
NSString *path1=[[NSString alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"YOUR_CSV_FILENAME" ofType:#"csv"] usedEncoding:&encoding error:nil];
NSArray *messArr=[path1 componentsSeparatedByString:#"\n"];
if(messArr)
{
for(int i=1;i<=[messArr count]-2;i++)
{
NSMutableDictionary *d=[[NSMutableDictionary alloc] init];
NSString *StrValue=[NSString stringWithFormat:#"%#",[messArr objectAtIndex:i]];
StrValue=[StrValue stringByReplacingOccurrencesOfString:#"\"" withString:#""];
StrValue=[StrValue stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// Here give whatever saperator you need to saperate data
NSArray *arr=[StrValue componentsSeparatedByString:#","];
[d setValue:[arr objectAtIndex:0] forKey:#"YOUR_TABLE_FIELD_1"];
[d setValue:[arr objectAtIndex:1] forKey:#"YOUR_TABLE_FIELD_2"];
[d setValue:[arr objectAtIndex:2] forKey:#"YOUR_TABLE_FIELD_3"];
//Here add logic to insert row in your database table
}
}
i done with below code you need to just impliment that:-
-(void)restore{
#try {
NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:#"%#%#?userid=%#",kHOSTPATH,kCSVLIST,[[cntrAppDelegate setServerDetails] valueForKey:#"kUSERID"]]];
NSMutableURLRequest *requestMutable = [[NSMutableURLRequest alloc] init];
[requestMutable setURL:url];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:requestMutable returningResponse:&response error:&error];
NSLog(#"Response code: %d", [response statusCode]);
if ([response statusCode] >=200 && [response statusCode] <300)
{
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"Response ==> %#", responseData);
SBJsonParser *jsonParser = [SBJsonParser new];
NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
NSLog(#"--------=========%#============-------------",jsonData);
NSDictionary *dic = [jsonData objectForKey:#"Root"];
NSLog(#"---------------------ROOT VALUE IS %#",dic);
NSLog(#"----------------COUNT IS %d",[dic count]);
for (int i = 0; i < [dic count]; i++)
{
NSString *str = [[dic valueForKey:#"CSV_File"]objectAtIndex:i];
NSLog(#"STR IS %#",str);
[self.arrListOfCSV addObject:str];
}
if ([jsonData valueForKey:#"Root"] == 0)
{
}
else
{
}
}
You should better import data in Linux. And in Disk Operation System after into the SQLite,enter
separator",";
importchoose your csv pathxyz. When you create table named xyz, the name should be agree with your csv files .

parsing json data giving error

Im fetching JSON data from this link.
http://www.krsconnect.no/community/api.html?method=event&appid=620&eventid=15946&affecteddate=1310515200000
I want to store all the required elemnts like image-medium title etc in aDetail object of Detail class but its giving error.
Here is my code:
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.krsconnect.no/community/api.html?method=event&appid=620&eventid=15946&affecteddate=1310515200000"]];
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];
for (int i=0; i<[results count]; i++) {
NSDictionary*dictOne=[results objectAtIndex:i];
Detail *aDetail = [[Detail alloc] initWithDictionary:[results objectAtIndex:i]];
[appDelegate.descriptionArray addObject:aDetail];
}
that's not how you use SBJSon. Try this:
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.krsconnect.no/community/api.html?method=event&appid=620&eventid=15946&affecteddate=1310515200000"]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSDictionary *object = [json_string JSONValue];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSError *error;
SBJSON *json = [[SBJSON new] autorelease];
id obj = [json objectWithString:json_string error:&error];
if ([obj isKindOfClass:[NSDictionary class]]) {
[appDelegate.descriptionArray addObject:obj];
}else if ([obj isKindOfClass:[NSArray class]]) {
for (NSDictionary *aDetail in obj) {
[appDelegate.descriptionArray addObject:aDetail];
}
}

Adding JSON data in array giving nil value

I have fetched the JSON data i want to store all the information like in a Book class object book and the use them by book.title etc.
I am using following code
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];
NSDictionary *dictOne = [results objectAtIndex:0];
/*
NSArray *activitiesArray = [dictOne objectForKey:#"events"];
NSDictionary *dictTwo = [activitiesArray objectAtIndex:0];
NSLog(#"%# - %#", [dictOne objectForKey:#"date"]);
NSLog(#"%# - %#", [dictTwo objectForKey:#"affectedDate"]);
*/
appDelegate.books = [[NSMutableArray alloc] init];
NSArray *activitiesArray = [dictOne objectForKey:#"events"];
NSDictionary *dictTwo = [activitiesArray objectAtIndex:0];
NSLog(#"%# - %#", [dictOne objectForKey:#"date"]);
NSLog(#"%# - %#", [dictTwo objectForKey:#"affectedDate"]);
I want to do like this store the data in an array but its not working
NSArray *results = [parser objectWithString:json_string error:nil];
for (int i=0; i<[results count]; i++) {
Book *aBook = [[Book alloc] initWithDictionary:[results objectAtIndex:i]];
[appDelegate.books addObject:aBook];
[aBook release];
}

How to store the parsed JSON data in a singl array

I have parsed JSON data the format of my JSON data is
http://www.krsconnect.no/community/api.html?method=bareListEventsByCategory&appid=620&category-selected=350&counties-selected=Vest-Agder,Aust-Agder
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.krsconnect.no/community/api.html?method=categories&appid=620&mainonly=true"]];
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];
How about creating a data modal?
#interface book:NSObject {
NSString *catId;
NSString *bookName
}
create properties for these two instance vars.
#end
#implementation book
#synthesize catId,bookName;
- (id)init {
self = [super init];
}
- (id)initWithDictionary:(NSDictionary) dict {
self.catId = [dict valueForKey:#"categoryId"];
self.bookName = [dict valueForKey:#"name"];
}
- (void)dealloc {
[catId release];
[bookName release];
[super dealloc];
}
#end
and use it like this
NSMutableArray *bookArray = [[NSmutableArray alloc] initWithCapacity:0];
NSArray *results = [parser objectWithString:json_string error:nil];
for (int i=0; i<[results count]; i++) {
book *bookObject = [[book alloc] initWithDictionary:[results objectAtIndex:i]];
[bookArray addObject:bookObject];
[bookObject release];
}
I think you can do this by way
Adding dictionary to array.
for (NSDictionary *dict in mydict) {
[myArray addObject:dict];
}
You can do more modification and put the logic to set the values in array according
to key as well.
Hope this may help you.Well I haven't checked it now.But may get you to the solution.
Cheers.....

How to read the JSON value on console in iphone

i have the following json value in console:
{"TokenID":"kuiHigen21","isError":false,"ErrorMessage":"","Result":[{"UserId":"153","FirstName":"Rocky","LastName":"Yadav","Email":"rocky#itg.com","ProfileImage":null,"ThumbnailImage":null,"DeviceInfoId":"12"}],"ErrorCode":900}
this is my server api :#"http://192.168.0.68:91/JourneyMapperAPI?RequestType=Login"
//api takes 5 parameters .
when i post data to server api values are posted to server and i get the above response in json format.
i want to parse the above the JSON value that i get in the response and save in sqlite database.
i am doing this code to parse the above JSON value:
-(void)connectionDidFinishLoadingNSURLConnection *)connection
{
NSString *loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] lengthwebData length] encoding:NSUTF8StringEncoding];
NSLog(#"%#",loginStatus);
self.webData = nil;
SBJSON *parser =[[SBJSON alloc]init];
NSURLRequest *request = [NSURLRequest requestWithURLNSURL URLWithString"http://192.168.0.68:91/JourneyMapperAPI?RequestType=Login.json"]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
//NSDictionary *object = [parser objectWithString:json_string error:nil];
// parse the JSON response into an object
// Here we're using NSArray since we're parsing an array of JSON status objects
NSArray *statuses = [parser objectWithString:json_string error:nil];
for (NSDictionary *status in statuses)
{
// You can retrieve individual values using objectForKey on the status NSDictionary
// This will print the tweet and username to the console
NSLog(#"%# - %#", [status objectForKey"Login"],[status objectForKey"LoginKey"]);
[connection release]; [webData release];
}
You should check out some of the JSON parsers, my personal favourite is json-framework. After you've included one of them in your project, where you've got your JSON response from your server:
// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSDictionary *result = [json_string JSONValue];
NSArray *statuses = [result objectForKey:#"Result"];
which will return your array of results (where each object in the array is an NSDictionary).
You can save this to a database with the help of a model class, Result
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSDictionary *result = [json_string JSONValue];
NSArray *values = [result objectForKey:#"Result"];
NSMutableArray *results = [[NSMutableArray alloc] init];
for (int index = 0; index<[values count]; index++) {
NSMutableDictionary * value = [values objectAtIndex:index];
Result * result = [[Result alloc] init];
result.UserId = [value objectForKey:#"UserId"];
result. FirstName = [value objectForKey:#"FirstName"];
...
[results addObject:result];
[result release];
}
use the array of results to save it to the database.
for (int index = 0; index<[results count]; index++) {
Result * result = [results objectAtIndex:index];
//save the object variables to database here
}