Can't save json in IOS [duplicate] - ios

This question already has answers here:
File write with [NSBundle mainBundle] fails
(5 answers)
Closed 7 years ago.
I can't save string to JSON on device, but in simulator can!
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"Warehouse" ofType:#"json"];
NSData *jsonData = [NSData dataWithContentsOfFile:filePath];
NSMutableArray *arJson = [[NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil] mutableCopy];
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:prod.title,#"title",
prod.price,#"price",
prod.descrip,#"descrip",nil];
[arJson addObject:dic];
NSData * data = [NSJSONSerialization dataWithJSONObject:arJson options:NSJSONWritingPrettyPrinted error:nil];
NSString * myString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
[[myString dataUsingEncoding:NSUTF8StringEncoding] writeToFile:filePath atomically:YES];

You can't change files in you main bundle folder. Check full answer here: https://stackoverflow.com/a/10671119/1003065

Related

How to parse JSON data in iOS objective-c [duplicate]

This question already has answers here:
How to parse JSON in Objective-C
(2 answers)
Closed 6 years ago.
I have JSON DATA
{"respcode":0,"policyid":"1731958","Insuredid":"5625869"}
How can I get respcode, policyid and Insuredid in individual variable using parsing.
Try out the below code:
NSString* path = [[NSBundle mainBundle] pathForResource:#"JSON" ofType:#"json"];
NSString* jsonString = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
NSDictionary *responseDictionary = [NSJSONSerialization
JSONObjectWithData:jsonData
options:0
error:&error];
if(! error) {
NSString *insuredId = [responseDictionary objectForKey:#"Insuredid"];
NSString *policyid = [responseDictionary objectForKey:#"policyid"];
NSString *respcode = [responseDictionary objectForKey:#"respcode"];
NSLog(#"insuredId : %# & policyid : %# & respcode : %#",insuredId,policyid,respcode);
} else {
NSLog(#"Error in parsing JSON");
}
//JSON.json
{"respcode":0,"policyid":"1731958","Insuredid":"5625869"}
Edited If your JSON DATA is already a Dictionary, you can access them using:
NSLog(#"%#",jsonData[#"respcode"]); // 0
NSLog(#"%#",jsonData[#"policyid"]); // 1731958
NSLog(#"%#",jsonData[#"Insuredid"]); // 5625869
I hope this can help you. If not, let me know more information about your code, so I can try a better answer.

NSJSONSerialization Returns Error of NULL

I have the following code :
NSData * jsonData = [NSData dataWithContentsOfURL:location];
NSString* newStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSData *data = [newStr dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError;
if (jsonError) {
NSLog(#"JSON Error %#", [jsonError localizedDescription]);
}
NSArray * jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&jsonError];
Which is parsing the following JSON String :
{"author":"Oli Riman","content":"The museum shows us a view of pre-WWI society that includes doubts, fears, political protests etc. through newspaper cartoons of the time. Really interesting for adults who enjoy history. I wouldn't suggest this for kids who haven't studied WWI history or who don't read easily.","rating":"5","placeId":"40","date":"29-June-2015","reviewId":"9905A52D-76B2-4D42-8CA8-9158225C0D07"}
However I am getting a strange error code of :
domain: (null) - code: 0
Can anyone advise on what is causing this ?
Just tested the code on my simulator. Its working. You need to check if you are getting data from server or not.
If you want to test the parsing thing, you can do one thing-
Just store the data in json file and save it in the app bundle lets say file is "data.json"
and call below method, you will get data for sure.
- (void)readJsonData {
NSString *path = [[NSBundle mainBundle] pathForResource:#"data" ofType:#"json"];
NSURL *url = [NSURL fileURLWithPath:path];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData: data
options: NSJSONReadingAllowFragments
error: &error];
NSLog(#"Parsed json data- %#", dict);
}

How to get the values from json service [duplicate]

This question already has an answer here:
Parsing JSON response .
(1 answer)
Closed 8 years ago.
Hai I need to get the id & status from the service for login my code is below. please guide me to get the values.. Thanks in advance..
NSString *Username= txtUsername.text;
NSString *Password=txtPassword.text;
NSString *link = [NSString stringWithFormat:#"http://www.xxx/login.php?user=%#&pass=%#&format=json",Username,Password];
NSURL *url=[NSURL URLWithString:link];
NSData *data=[NSData dataWithContentsOfURL:url];
1st Do the jSon parsing and then get the particular value from the
key .
Before getting any value , we have to understand the tree of jSon.
Here "posts" is an NSArray ,within that one DIctionary "post" is
there ,which again contains another dictionary.
Below is the complete code.
(void)viewDidLoad
{
[super viewDidLoad];
 NSString *Username= txtUsername.text;
NSString *Password=txtPassword.text;
NSString *link =
[NSString stringWithFormat:#"http://www.some.com/webservice/login.php?user=%#&pass=%#&format=json",Username,Password];
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL:
kLatestKivaLoansURL];
[self performSelectorOnMainThread:#selector(fetchedData:)
withObject:data waitUntilDone:YES];
}); }
Then call that selector fetchedData
(void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions
error:&error];
 
if(!error){
NSArray* postArray = [json objectForKey:#“posts”]; //This is an array
if (postArray.count>0) {
NSDictionary *dict = [[postArray objectAtIndex:0] objectForKey:#"post" ];
NSString *id_ = [dict objectForKey:#"id"];
NSString *status_ = [dict objectForKey:#"status"];
}
}
}
Can you post your json string. You can use NSJSONSERIALISATION to convert data (json string ) into NSDictionary. Then use the keys to extract the values. I'm replying through mobile so I can't write the actual code.
Use Below code to parse Json in IOS
NSString *Username= txtUsername.text;
NSString *Password=txtPassword.text;
NSString *link = [NSString stringWithFormat:#"http://www.some.com/_webservice/login.php?user=%#&pass=%#&format=json",Username,Password];
NSURL *url=[NSURL URLWithString:link];
NSMutableURLRequest *req1 = [NSMutableURLRequest requestWithURL:url];
NSURLResponse *response;
NSError *error;
//getting the data
NSData *newData = [NSURLConnection sendSynchronousRequest:req1 returningResponse:&response error:&error];
NSString *responseString = [[NSString alloc] initWithData:newData encoding:NSUTF8StringEncoding];
NSLog(#"basavaraj \n\n\n %# \n\n\n",responseString);
NSData* data = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&myError];
NSString *id=[res objectForKey:#"ID"];
NSString *status=[res objectForKey:#"Status"];
and if u need extra info please go through below link it may help you
Click here for more details

Convert Localizable.strings to json

I want to convert Localizable.strings file to JSON:
"Key" = "Localized Str";
To
"Key" : "Localized Str",
Is there any ready solution? Or better write own script?
NSString *path = [[NSBundle mainBundle] pathForResource:#"Localizable"
ofType:#"strings"
inDirectory:nil
forLocalization:#"en"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict
options:NSJSONWritingPrettyPrinted
error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

iOS - How to get more debugging information on nil return values

In my iOS 5.1 application, I'm trying to load a JSON text file into a NSDictionary.
NSString *filepath = [[NSBundle mainBundle] pathForResource:#"stuff" ofType:#"json"];
NSDictionary *stuff = [NSDictionary dictionaryWithContentsOfFile:filepath];
The filepath is valid, the file exists, but stuff is nil, which means there was a problem decoding the file (according to the documentation).
(How) Can I get more debugging information on why [NSDictionary dictionaryWithContentsOfFile:] - or any kind of API call - returns nil?
Read the contents as NSData and then use +[NSPropertyListSerialization propertyListWithData:options:format:error:].
As you said: Your file contains a JSON string. First, you have to load the string and then you have to parse it using some JSON library.
E.g.:
NSError *error;
NSString *content = [NSString stringWithContentsOfFile:filepath encoding:NSUTF8StringEncoding error:&error]; //error checking omitted
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *json = [parser objectWithString: content];

Resources