I am working on JSON data parsing with lots of images downloading and data parsing.I have following code for parsing
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *responseString = [[NSString alloc] initWithData:webdata encoding:NSASCIIStringEncoding];
[webdata release];
[connection release];
NSDictionary *values = [(NSDictionary*)[responseString JSONValue] objectForKey:#"UserId"];
NSDictionary *Active = [(NSDictionary*)[responseString JSONValue] objectForKey:#"Active"];
[responseString release];
NSString *UserID=[NSString stringWithFormat:#"%#",values];
NSString *Status=[NSString stringWithFormat:#"%#",Active];
[WSDelegate WServiceResponseMsg:#"WS_Authenticate_User" withResponse:UserID forParam:Status];
}
I have many classes with above code for parsing but app crashes after some time interval because of SBJSON parser.In instrument it gives app crashed because of low memory warning.
It is a very wrong assumption that most of the developers have while using SBJSONParser that, it has memory leaks. SBJSONParser does not has any leaks and does not introduces leaks in your code.
It is true that INSTRUMENTS tells you that the leak is because of SBJSONParser, but it denotes something else. Leaks are because of the way you have implemented SBJSONParser APIs. You must have done something wrong in your code.
Go to the leaks in your instruments. Open Extended Details toolbar and see the line of code that has leak. Instruments tells you the nearest place where the leak is.
Better option would be to use NSJSONSerialization that come as a part with iOS 5 and above
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSMutableDictionary *values = [NSJSONSerialization JSONObjectWithData:receivedData options:NSJSONReadingMutableContainers error:&error];
}
Finally got solution.Just use below line for JSON parsing.Remove NSMutableDictionary and use id :
NSError *jsonError = nil;
id allValues = [NSJSONSerialization JSONObjectWithData:webdata
options:0
error:&jsonError];
NSArray *array = [allValues objectForKey:#"Contestants"];
I need to send an NSArray to the server in the JSON array format. How can I convert it to JSON. This is a sample of my NSArray that I have to pass.
array([0] => array('latitude'=>'10.010490',
'longitude'=>'76.360779',
'altitude'=>'30.833334',
'timestamp'=>'11:17:23',
'speed'=>'0.00',
'distance'=>'0.00');
[1] => array('latitude'=>'10.010688',
'longitude'=>'76.361378',
'altitude'=>'28.546305',
'timestamp'=>'11:19:26',
'speed'=>'1.614',
'distance'=>'198.525711')
)`
and the required format is like this
[
{ "latitude":"10.010490",
"longitude":"76.360779",
"altitude":"30.833334",
"timestamp":"11:17:23",
"speed":"0.00",
"distance":"0.00"
},
{
"latitude":"10.010688",
"longitude":"76.361378",
"altitude":"28.546305",
"timestamp":"11:19:26",
"speed":"1.614",
"distance":"198.525711"
}
]
Any one have solution? Thanks in advance.
NSDictionary *firstJsonDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
#"10.010490", #"latitude",
#"76.360779", #"longitude",
#"30.833334", #"altitude",
#"11:17:23", #"timestamp",
#"0.00", #"speed",
#"0.00", #"distance",
nil];
NSDictionary *secondJsonDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
#"10.010490", #"latitude",
#"76.360779", #"longitude",
#"30.833334", #"altitude",
#"11:17:23", #"timestamp",
#"0.00", #"speed",
#"0.00", #"distance",
nil];
NSMutableArray * arr = [[NSMutableArray alloc] init];
[arr addObject:firstJsonDictionary];
[arr addObject:secondJsonDictionary];
NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];
NSLog(#"jsonData as string:\n%#", jsonString);
The simplest and best approach !!!
To convert NSArray or NSMutableArray into jsonString you can first convert it into NSData and then further convert that into a NSString. Use this code
NSData* data = [ NSJSONSerialization dataWithJSONObject:yourArray options:NSJSONWritingPrettyPrinted error:nil ];
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
It helped me and hope it helps you as well. All the best.
I would recommend the SBJson-Framework.
Converting an NSMutableArray is as simple as NSString *jsonString = [yourArray JSONRepresentation];
Edit: Jack Farnandish is right u have to transform it into a NSDictionary before you can convert it to Json. In my example the NSMutableArray has to contain the Dictionary. The Array is only needed to create the square brackets at the beginning and the end of the string.
You can use the build in JSON functions of iOS or use an external lib e.g. JSONKit to convert your data to JSON
First You must change you structure into NSDictionary class and NSArray containing NSDictionary objects, then try JSONKit in iOS 5 serialization works better than standard NSJSONSerialization.
#import <JSONKit/JSON.h>
NSArray *array = // Your array here.
NSString *json = [array JSONString];
NSLog(#"%#", json);
JSONKit performs significantly better than SBJson and others in my own and the author's benchmarks.
Check this tutorial, JSON in iOS 5.0 was clearly explained (serailization, deserailization).
Is the service you are calling a RESTful service?
If so, I'd strongly recommend using RestKit. It does object serialization/deserialization. It also handles all the networking underpinnings. Extremely valuable, and well maintained.
This feels like a super newb question, so apologizes in advance.
How does one specify booleans when using NSJSONSerialization?
My current code is below:
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:
value, #"key",
NO, #"booleanKey",
nil];
NSData *jsondata = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsondata encoding:NSUTF8StringEncoding];
It just seems to be ignoring it and the NSLog output looks like:
{"key":"THE VALUE OF id value"}
The reason that it is getting ignored is because NO is the same as nil, which terminates your dictionary list. You can only add objects into your dictionary, thus turn any primitive types into objects. E.g.: NO turns to [NSNumber numberWithBool:NO] or if you are using Xcode 4.4 you can just use #(NO).
Try with:
[NSNumber numberWithBool: NO]
instead using the bool value directly.
You can check the doc here.
I want get image from public perfil of Facebook and show it in my iPhone. I'm using the Facebook Developer method "graph.facebook.com" and later i want read it with JSON, but when i save data in NSArray, it SIGABRT.
NSURL *myURL = [NSURL URLWithString:url];
NSData *datosAlbum = [[NSData alloc] initWithContentsOfURL:myURL];
NSError *error=nil;
NSString *datosString=[[NSString alloc] initWithData:datosAlbum encoding:NSUTF8StringEncoding];
[datosAlbum release];
SBJsonParser *parser=[[SBJsonParser alloc]init];
NSLog(#"%#",[parser objectWithString: datosString error: &error]);
NSArray *datos_array= [[NSArray alloc]initWithArray:[parser objectWithString: datosString error: &error]];
Can someone help me?
Thanks for all and Merry Christmas!
Best Regards!
Try: https://graph.facebook.com/4/picture
and for the json https://graph.facebook.com/4
I am trying to make a google reader app. I am able to get the subscription list in JSON format like this:
{"subscriptions":[{"id":"feed/http://aspn.activestate.com/ASPN/Cookbook/Python/index_rss","title":"ActiveState Code: Python recipes","categories":[{"id":"user/014533032765194560dwd0/label/Programming","label":"Programming"}],"sortid":"E6312EFB","firstitemmsec":"1258141669516","htmlUrl":"http://code.activestate.com/recipes/langs/python/"},
I am interested in getting the label value (in the above case "Programming") into an array. Here is my current code:
-(BOOL)parsedSuccess {
SBJsonParser *parser = [[SBJsonParser alloc]init];
if (!receivedData) {
[self getSubscriptionList:GOOGLE_READER_SUBSCRIPTION_LIST];
}
NSMutableString *body = [[NSMutableString alloc]initWithData:receivedData encoding:NSUTF8StringEncoding];
if (body) {
NSArray *feeds = [parser objectWithString:body error:nil];
NSDictionary *results = [body JSONValue];
NSArray *subs = [results valueForKey:#"subscriptions"];
NSString *subTitles;
for (NSDictionary *title in subs){
subTitles = [title objectForKey:#"categories"];
NSLog(#"%#",subTitles);
}
}
return YES;
}
Can someone help me in getting the label values?
[[[[[result valueforkey:#"subscription"]objectatindex:0]valueforkey:#"categories"]objectatindex:intvalue]valueforkey:#"label"];
I just helped to make logic. Be sure to check for spelling mistakes before implementing.