how to read local json file using objective-c [duplicate] - objective-c

This question already has answers here:
How do I parse JSON with Objective-C?
(5 answers)
Closed 9 years ago.
I am new to iOS, please help me how can I read a local JSON file using objective-c
SBJSON *parser = [[SBJSON alloc] init];
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"auth_request" ofType:#"json"];
NSError *error = nil;
NSData *JSONData = [NSData dataWithContentsOfFile:filePath options:NSDataReadingMappedIfSafe error:&error];
NSString *json_string = [[NSString alloc] initWithData:JSONData encoding:NSUTF8StringEncoding];
NSArray *statuses = [parser objectWithString:json_string error:nil];
for (NSDictionary *status in statuses) {
NSLog(#"%# - %#", [status objectForKey:#"loginId"], [status objectForKey:#"secret"]);
}

Just Add
NSArray *tempArray = [json_string JSONVALUE]
in the place of
NSArray *statuses = [parser objectWithString:json_string error:nil];
Don't forget to import

Related

Method always re-writing json file

NSURL *url = [NSURL URLWithString:#"file://localhost/Users/admin/Desktop/JSON/vivijson.json"];
NSDictionary *regDict = [[NSDictionary alloc] initWithObjectsAndKeys:self.loginString, #"login",
self.nameString, #"name",
self.lastNameString, #"lastName",
self.emailString, #"email",
self.numberString, #"number", nil];
NSError *error;
NSMutableArray *regMutArray = [[NSMutableArray alloc] init];
[regMutArray addObject:regDict];
NSData *jsonConvRegArrayData = [NSJSONSerialization dataWithJSONObject:regMutArray options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonRegString = [[NSString alloc] initWithData:jsonConvRegArrayData encoding:NSUTF8StringEncoding];
[jsonConvRegArrayData writeToURL:url atomically:YES];
This method are re-writing JSON, and start it again, but i need to add some to my JSON.
You should first read the exiting JSON into a mutable array using JSONObjectWithData using NSJSONReadingMutableContainers as the reading options. Then add the new array element to the mutable array returned by JSONObjectWithData and then convert it back to an JSON using dataWithJSONObject
Here's the code.
NSURL *url = [NSURL URLWithString:#"file://localhost/Users/Shared/vivijson.json"];
NSDictionary *regDict = [[NSDictionary alloc] initWithObjectsAndKeys:#"self.loginString, #"login",
self.nameString, #"name",
self.lastNameString, #"lastName",
self.emailString, #"email",
self.numberString, #"number", nil];
NSError *error;
NSMutableArray *regMutArray = [[NSMutableArray alloc] init];
[regMutArray addObject:regDict];
NSData *data = [NSData dataWithContentsOfURL:url];
NSMutableArray *array = nil;
if (data)
array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
if (array == nil)
{
array = [[NSMutableArray alloc] init];
}
[array addObjectsFromArray:regMutArray];
NSData *jsonConvRegArrayData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonRegString = [[NSString alloc] initWithData:jsonConvRegArrayData encoding:NSUTF8StringEncoding];
[jsonRegString writeToURL:url atomically:true encoding:NSUTF8StringEncoding error:nil];

Unable to convert a string to a NSURL

I am trying to turn off WAL in CoreData using this code:
// Code to disable journaling mode
NSString *applicationDocumentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *urlString = [applicationDocumentsDirectory stringByAppendingPathComponent: #"saori.sqlite"];
NSURL *url = [[NSURL alloc] initWithString:urlString];
NSDictionary *options = #{NSSQLitePragmasOption:#{#"journal_mode":#"DELETE"}};
NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] init];
[psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:options error:nil];
This is my NSString that I need to convert to a URL:
/Users/rolfmarsh/Library/Application Support/iPhone Simulator/7.1/Applications/7A614C51-AC51-4F5B-9716-6E3D2F160324/Documents/saori.sqlite
When I use that string in this statement, it generates nil.
NSURL *url = [[NSURL alloc] initWithString:urlString];
I don't see anything wrong with the string. What am I doing wrong?
Read the docs for NSURL. You have a file path and you need to create a file URL from the file path.
NSURL *url = [NSURL fileURLWithPath:urlString];

How to save data locally in app? [duplicate]

This question already has answers here:
Working with data in iOS Apps (What to choose? NSData, CoreData, sqlite, PList, NSUserDefaults)
(2 answers)
Closed 9 years ago.
I've been struggling with this for ages now and I really need some good help here. :)
I have an app where I'm parsing a quite big JSON into appdelegate's didFinishLaunchingWithOptions.
My Model Objects are:
Tab:
NSString *title
NSMutableArray *categories
Category:
NSString *title
NSMutableArray *items
Item
NSString *title
NSString *description
UIImage *image
I need to save the data locally, cause the parsing takes about 15 seconds every time my app starts. I'm using the SBJSON framework.
Here's my code for parsing:
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"json_template" ofType:#"json"];
NSString *contents = [NSString stringWithContentsOfFile: filePath encoding: NSUTF8StringEncoding error: nil];
SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
NSMutableDictionary *json = [jsonParser objectWithString: contents];
tabs = [[NSMutableArray alloc] init];
jsonParser = nil;
for (NSString *tab in json)
{
Tab *tabObj = [[Tab alloc] init];
tabObj.title = tab;
NSDictionary *categoryDict = [[json valueForKey: tabObj.title] objectAtIndex: 0];
for (NSString *key in categoryDict)
{
Category *catObj = [[Category alloc] init];
catObj.name = key;
NSArray *items = [categoryDict objectForKey:key];
for (NSDictionary *dict in items)
{
Item *item = [[Item alloc] init];
item.title = [dict objectForKey: #"title"];
item.desc = [dict objectForKey: #"description"];
item.url = [dict objectForKey: #"url"];
if([dict objectForKey: #"image"] != [NSNull null])
{
NSURL *imgUrl = [NSURL URLWithString: [dict objectForKey: #"image"]];
NSData *imageData = [NSData dataWithContentsOfURL: imgUrl];
item.image = [UIImage imageWithData: imageData];
}
else
{
UIImage *image = [UIImage imageNamed: #"standard.png"];
item.image = image;
}
[catObj.items addObject: item];
}
[tabObj.categories addObject: catObj];
}
[tabs addObject: tabObj];
}
What is the best way of doing this? Using Core Data or NSFileManager?
If you have som code example too it will make me very happy.
This is the last thing i need to fix before the app is ready for app store and it just kills me! I can't solve this problem.
If you are working on iOS then you save a file to the Documents folder. On Mac OS X it would be in the Application Support folder. Since you are on iOS, read this answer for how to access the Documents folder.
All of the objects that you want to store should implement NSCoding. The above variables already do. Should you want to store the tabs, categories and items directly they would need to implement NSCoding. Then all you need is to serialize them to a file. When opening you app you can look for this file and get your objects back without parsing.
The code should look something like this (untested and error checking is ommited for brevity):
- (void) saveStateToDocumentNamed:(NSString*)docName
{
NSError *error;
NSFileManager *fileMan = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [paths[0] stringByAppendingPathComponent:docName];
if ([fileMan fileExistsAtPath:docPath])
[fileMan removeItemAtPath:docPath error:&error];
// Create the dictionary with all the stuff you want to store locally
NSDictionary *state = #{ ... };
// There are many ways to write the state to a file. This is the simplest
// but lacks error checking and recovery options.
[NSKeyedArchiver archiveRootObject:state toFile:docPath];
}
- (NSDictionary*) stateFromDocumentNamed:(NSString*)docName
{
NSError *error;
NSFileManager *fileMan = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [paths[0] stringByAppendingPathComponent:docName];
if ([fileMan fileExistsAtPath:docPath])
return [NSKeyedUnarchiver unarchiveObjectWithFile:docPath];
return nil;
}

parse JSON in objectiveC (SBJSON) objects and arrays

So far I've discovered in JSON that everything enclosed in { } are objects (objC : NSDictionary) and anything enclosed in [ ] is an array (objC : NSArray).
I've read and re-read this article about the subject>
How to parse JSON into Objective C - SBJSON
I have a .json file with the data modeled like this:
http://elbee101.com/dummySchedule.json
...and now for the code:
SBJSON *parser = [[SBJSON alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://elbee101.com/dummySchedule.json"]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSDictionary *schedule = [parser objectWithString:json_string error:nil];
NSDictionary *day = [schedule objectForKey:#"day"];
NSArray *myList = [day objectForKey:#"name"];
NSLog(#"myList %#", myList);
NSArray *numLaps = [myList objectAtIndex:0];
NSLog(#"numlaps%# ", numLaps);
I'm getting "myList (null)" and "numlaps (null)" from the above code?!#
The question: Can somebody please set me straight on the ordering of objects and arrays with respect to my json data? I want to drill down the tree so that I can access the 'day name', 'session starttime/endtime/sessionname', 'numlaps' & 'class' but I can't seem to get past the 'day' object/array(?)
What you're referring to as schedule is the object enclosed in the outermost {}. Try this:
NSDictionary *json = [parser objectWithString:json_string error:nil];
NSDictionary *schedule = [json objectForKey:#"schedule"];
Then continue as before.
Also, if you're on iOS 5 you can use the NSJSONSerialization class -- using it is pretty much the same, you might get better performance, and you don't have to worry about the hassles of using a third-party library.
call this where ever u need to parse
NSMutableArray *arr=[[NSMutableArray alloc] init];
arr=[[Headparse getArrayFromUrl:#"http://elbee101.com/dummySchedule.json"] retain];
NSLog(#"%#",[arr description]);
[arr release];
write this method as custom class use when ever you need
+(NSMutableArray *) getArrayFromUrl: (NSString *)actionType
{
NSMutableData *responseData1= [NSMutableData data] ;
responseData1 = [NSMutableData dataWithContentsOfURL:[NSURL URLWithString:actionType]];
// NSLog(#"%#",responseData1);
NSString *responseString1 = [[NSString alloc] initWithData:responseData1 encoding:NSUTF8StringEncoding];
//NSLog(#"REs:-->%#",responseString1);
//[responseData1 release];
responseData1 = nil;
NSMutableArray *responseArray = [[NSMutableArray alloc]init];
responseArray = (NSMutableArray *)[responseString1 JSONValue];
// NSLog(#"ghfchfvghv%#",responseArray);
[responseString1 release];
return responseArray;
}
This is how i use NSJsonSerialization for parsing the json object.
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://elbee101.com/dummySchedule.json"]];
NSError *err;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&err]; //
NSDictionary *schedule_dict = [json objectForKey:#"schedule"];
NSArray *days = [schedule_dict objectForKey:#"day"];//Days Array from day Object
NSDictionary *dayOne = [days objectAtIndex:0];
NSDictionary *dayTwo = [days objectAtIndex:1];
NSLog(#"THE DAY ONE : %#",dayOne);
NSLog(#"THE DAY TWO : %#",dayTwo);
Hope this may help you ....Note : If you don't want to go with NSJsonSerailization(consider reading of this) ,but still the parsing of json data like above will applicable in your case too.

How to Parse JSON Data and display in it in an iPhone Applicaiton

I want to parse the following given all the data in and array then use in iPhone application to display.
http://www.krsconnect.no/community/api.html?method=fullEvents&appid=620
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.krsconnect.no/community/api.html?method=fullEvents&appid=620"]];
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:#"activities"];
NSDictionary *dictTwo = [activitiesArray objectAtIndex:0];
NSDictionary *eventDict = [dictTwo objectForKey:#"event"];
NSDictionary *dictThree = [activitiesArray objectAtIndex:0];
NSDictionary *eventDict3 = [dictThree objectForKey:#"images"];
NSLog(#"%# - %#", [eventDict3 objectForKey:#"large"]);
NSLog(#"%# - %#", [eventDict objectForKey:#"category"]);
NSLog(#"%# - %#", [eventDict objectForKey:#"content"]);
It's working fine but if I print HoursFrom from dates object it's not printing
That'll be because in your data feed, it's hoursFrom, not HoursFrom. The case is significant.