exc_breakpoint while JSON parsing - iphone

I want to parse many JSON strings. Here is the code:
while(stations.count > 0) {
NSString*string = [[[NSString alloc] initWithString:[stations objectAtIndex:0]] retain];
NSMutableDictionary*dic = [[[NSMutableDictionary alloc]init]retain];
NSData*data = [[[NSData alloc] initWithData:[string dataUsingEncoding:NSUTF8StringEncoding]]retain];
NSMutableDictionary* pars = [[NSMutableDictionary alloc]initWithDictionary:[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]];
[dic setObject:[NSString stringWithString:[pars objectForKey:#"nm"]] forKey:#"nm"];
[dic setObject:[NSString stringWithString:[pars objectForKey:#"btr"]] forKey:#"btr"];
[dic setObject:[NSString stringWithString:[pars objectForKey:#"id"]] forKey:#"id"];
[dic setObject:[NSString stringWithString:[pars objectForKey:#"cntr"]] forKey:#"cntr"];
[dic setObject:[NSString stringWithString:[pars objectForKey:#"gnr"]] forKey:#"gnr"];
[pars release];
#try {
[parsedData addObject:[NSDictionary dictionaryWithDictionary:dic]];
}
#catch (NSException* exc) {
NSLog(#"%#, %#", exc.description, exc.reason);
}
[dic release];
[data release];
[string release];
[stations removeObjectAtIndex:0];
if (i%1000==0) {
NSLog(#"nnnn %i %i", parsedData.count, stations.count);
}
i++;
float k = count;
k = (i + 1)/k;
[self performSelectorOnMainThread:#selector(increaseProgress:) withObject:[NSNumber numberWithFloat:k] waitUntilDone:YES];
}
On adding (usually but not every time) string to array I get error:
exc_breakpoint (code=exc_i386_bpt
and:
GuardMalloc[Radiocent new try-1820]: Failed to VM allocate 68752 bytes
GuardMalloc[Radiocent new try-1820]: Explicitly trapping into debugger!!!
Stations array is pretty big... about 60000 strings.

First of all when you alloc you don't need to retain as retain count is already +1.
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
Not
NSMutableDictionary*dic = [[[NSMutableDictionary alloc]init]retain];
Below line already returs mutable dictionary so you don't have to create a new dictionary out of that and if you want to change then just call a - mutableCopy on it.
NSMutableDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
or to create a copy:
NSMutableDictionary *dictionary = [[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil] mutableCopy];
If stations is JSON string then for all stations do this:
NSData *data = [JSONString dataUsingEncoding:NSUTF8StringEncoding];
NSArray *stationsArray = [[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil] mutableCopy];
for (NSDictionary *stationDic in stationArray)
{
// This will iterate over each station dictionary in the station array
// Do your stuff here ...
}
For your example: (I have added \" to escape the double quotes, you don't have to)
Placed square brackets around your example this make it an array and you can iterate through each using the given code below. (Add only if they are not there)
NSString *example = #"[{\"id\":\"02AB99\",\"btr\":\"24\",\"cntr\":\"461E\",\"gnr\":\"8A51\",\"nm\":\"88.3 Fm Radio Q Jogjakarta\"}, {\"id\":\"026058\",\"btr\":\"160\",\"cntr\":\"461E\",\"gnr\":\"8A7B\",\"nm\":\"88.3 The Dog\"}, {\"id\":\"0300D2\",\"btr\":\"55 64\",\"cntr\":\"461C\",\"gnr\":\"8A75\",\"nm\":\"88.3 The Wind\"}, {\"id\":\"0159E6\",\"btr\":\"128\",\"cntr\":\"4610\",\"gnr\":\"8A6C\",\"nm\":\"88.30 Z Fm Radio Word Online\"}]";
NSError *error = nil;
NSArray *stationArray = [NSJSONSerialization JSONObjectWithData:[example dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:&error];
if (!error)
{
for (NSDictionary *stationDic in stationArray)
{
NSLog(#"\nName: %# \nDump: \n%#", [stationDic valueForKey:#"nm"], stationDic);
}
}

Related

How to retrieve all country name with counting to NSArray from NSDictionary?

Here is my dictionary result.
"continent_code" = EU;
"country_code" = gb;
"country_id" = 169;
"country_name" = "United Kingdom";
NSString *responseString = [[NSString alloc] initWithData:responseData
encoding:NSUTF8StringEncoding];
NSDictionary *LoginResult = (NSDictionary*)[responseString JSONValue];
I want to retrieve only country name to NSArray from dictionary.
Try This ::
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:webData options:NSJSONReadingMutableContainers error:&error];
NSLog(#" Value :: %#", [[jsonArray JSONRepresentation] JSONValue]);
for (NSDictionary *item in jsonArray) {
NSLog(#" Item :::::> %#", [item objectForKey:#"country_name"]);
}
Hope, It'll help you.
NSMutableArray *wholeJsonArray = [LoginResult objectForKey:#"RootName"];
NSMutableArray *loginArray = [[NSMutableArray alloc]init];
for(int i = 0 ; i<[loginArray count];i++)
{
NSString *countryName=[[loginArray objectAtIndex:i]objectForKey:#"country_name"];
[loginArray addObject:countryName];
}
Good luck !!
The Correct Method to fill countryArray :
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:yourResponseData options:kNilOptions error:&error];
NSArray* getMAS_CR = [(NSDictionary*)json objectForKey:#"yourKeyRootResult"];
NSMutableArray *countryArray = [[NSMutableArray alloc]init];
for (NSDictionary *rr in getMAS_CR)
{
NSString *cName = [NSString stringWithFormat:#"%#",[rr objectForKey:#"country_name"]];
[countryArray addObject:cName];
}
NSLog(#"countryArray :: %#",countryArray);
GoodLuck.

How to copy custom NSObject into NSMutableArray

NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
NSArray* users = [json objectForKey:#"Users"];
NSEnumerator* enumerator = [users objectEnumerator];
id element;
NSMutableArray *results;
Result *fetchedResults;
while(element = [enumerator nextObject]) {
// fetchedResults = [[Result alloc] init]; // i have tried commenting/uncommenting
fetchedResults.name = (NSString *)[[element objectForKey:#"User"] objectForKey:#"name"];
fetchedResults.email = (NSString *)[[element objectForKey:#"User"] objectForKey:#"name"];
NSLog(#"%#", fetchedResults.name);
[results addObject:fetchedResults];
NSLog(#"%#", (NSString *)[[element objectForKey:#"User"] objectForKey:#"name"]); // this returns valid dump
}
NSLog(#"%d", [results count]); // returns 0
I don't understand wht's wrong here. I have searched through numerous tutorials and resources don't seem to get what's wrong here.
EDIT:
NSLog(#"%#", fetchedResults.name); // dumps null
You forgot to allocate your results array NSMutableArray *results = [[NSMutableArray alloc] init] this should help.
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
NSArray* users = [json objectForKey:#"Users"];
NSMutableArray *results = [[NSMutableArray alloc] init];
for (id object in users) {
Result *fetchedResults = [[Result alloc] init];
fetchedResults.name = (NSString *)[[element objectForKey:#"User"] objectForKey:#"name"];
fetchedResults.email = (NSString *)[[element objectForKey:#"User"] objectForKey:#"name"];
NSLog(#"%#", fetchedResults.name);
[results addObject:fetchedResults];
}
NSLog(#"%#", (NSString *)[[element objectForKey:#"User"] objectForKey:#"name"]);
}
NSLog(#"%d", [results count]); // returns 0

Using SBJson, how to retrieve list of strings from array of objects? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Parse JSON in Objective-C with SBJSON
I have below JSON Response (String). I want to parse it into an NSArray with all the patient names.
[{"pat_reg_no":"111181031P1","app_start_time":"10.15","pat_firstname":"Will Smith"},
{"pat_reg_no":"111181031P2","app_start_time":"11.15","pat_firstname":"Shane Watson"},
{"pat_reg_no":"111181031P3","app_start_time":"12.15","pat_firstname":"Michael Hussey"},
{"pat_reg_no":"111181031P1","app_start_time":"10.15","pat_firstname":"Will Smith"}]
How do I parse this?
I write a demo for you.
SBJsonParser *parser = [[SBJsonParser alloc] init];
id jsonObj = [parser objectWithString:#"[{\"pat_reg_no\":\"111181031P1\",\"app_start_time\":\"10.15\",\"pat_firstname\":\"Will Smith\"},{\"pat_reg_no\":\"111181031P2\",\"app_start_time\":\"11.15\",\"pat_firstname\":\"Shane Watson\"},{\"pat_reg_no\":\"111181031P3\",\"app_start_time\":\"12.15\",\"pat_firstname\":\"Michael Hussey\"},{\"pat_reg_no\":\"111181031P1\",\"app_start_time\":\"10.15\",\"pat_firstname\":\"Will Smith\"}]"];
if ([jsonObj isKindOfClass:[NSArray class]]) {
for (id obj in jsonObj) {
if ([obj isKindOfClass:[NSDictionary class]]) {
NSString *name = [obj objectForKey:#"pat_firstname"];
NSLog(#"name %#", name);
}
}
}
[parser release];
Try Below Code.
NSString* jsonString;
//jsonString suppose this String has That JSON Response.
SBJSON *parser = [[[SBJSON alloc] init] autorelease];
NSDictionary *jsonResponse = (NSDictionary*)[parser objectWithString:jsonString error:nil];
NSArray *pat_reg_noArray = [jsonResponse valueForKey:#"pat_reg_no"] ;
NSArray *app_start_timeArray= [jsonResponse valueForKey:#"app_start_time"] ;
NSArray*firstnameArray=[jsonResponse valueForKey:#"pat_firstname"];
I hope It 'll work.
The Array which you have posted belongs to someKey, so do the following
SBJSON *jsonParser = [[SBJSON alloc] init];
NSDictionary * dictionary = [jsonParser objectWithString:YourString];
NSArray * array = [dictionary objectForKey:someKey];
NSMutableArray *nameArray = [NSMutableArray new];
for (NSDictionary *dict in array)
{
[nameArray addObject:[dict objectForKey:#"pat_firstname"];
}
NSLog(#"x is %#",nameArray);
[jsonParser release];
Hope this will solve your problem...
Try this:
NSString *jsonString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSArray* array = [(NSDictionary*)[jsonString JSONValue] objectForKey:#"results"];

sending NSDictionary with openURL

I want to open an other application using
[[UIApplication sharedApplication]openURL:[[NSURL alloc]initWithString:myString]];
as log as myString is like
NSString *myString=[NSString stringWithFormat:#"testHandleOpenUrl://?%#",#"123"];
it works fine but if I try to use an NSDictionary like
NSString *myString=[NSString stringWithFormat:#"testHandleOpenUrl://?%#",userInfo];
it fails without an error
Hope you can help me.
Try enumerating all the elements in your dictionary and appending those to your URL.
NSMutableString *params = [[[NSMutableString alloc] init] autorelease];
NSEnumerator *keys = [userInfo keyEnumerator];
NSString *name = [keys nextObject];
while (nil != name) {
[params appendString: name];
[params appendString: #"="];
[params appendString: [userInfo objectForKey:name]];
name = [keys nextObject];
if (nil != name) {
[params appendString: #"&"];
}
}
NSString *myString=[NSString stringWithFormat:#"testHandleOpenUrl://?%#",params];
When you use an NSDictionary in the format string, you get a URL that looks like this:
testHandleOpenUrl://?{
bar = foo;
}
The result of calling -description on userInfo is simply substituted for the %#. Presumably, you want to pass parameters contained in the dictionary in the URL. Probably something like this:
NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:#"bar", #"foo", nil];
NSString *myString=[NSString stringWithFormat:#"testHandleOpenUrl://?foo=%#", [userInfo objectForKey:#"foo"]];
NSLog(#"myString: %#", myString); // prints "myString: testHandleOpenUrl://?foo=bar"
NSString * paramString = #"";
int i = 0;
for(NSString * key in [userInfo allKeys]){
NSString * value = (NSString*)[userInfo objectForKey:key];
NSString * valueParam = [NSString stringWithFormat:#"%#%#=%#",(i==0)?#"?":#"&",key,value];
paramString = [paramString stringByAppendingString:valueParam];
i++;
}
NSString *myString=[NSString stringWithFormat:#"testHandleOpenUrl://%#", paramString];

Parsing JSON showing nil value

I am parsing the data it gets all the data in dictionary but when i check value using NSLog it showa nil value
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];
//appDelegate.books = [[NSMutableArray alloc] initWithCapacity:0];
appDelegate.books1 = [[NSMutableArray alloc] init];
NSArray *results = [parser objectWithString:json_string error:nil];
for (int i=0; i<[results count]; i++) {
Book1 *aBook = [[Book1 alloc] initWithDictionary:[results objectAtIndex:i]];
[appDelegate.books1 addObject:aBook];
Book1 *mybook=[appDelegate.books1 objectAtIndex:i];
NSString*test=mybook.location;
NSLog(test);
}
Dicionary parsing
- (id)initWithDictionary:(NSDictionary*) dict {
self.date = [dict valueForKey:#"date"];
self.location = [dict valueForKey:#"location"];
self.municipality = [dict valueForKey:#"municipality"];
self.title = [dict valueForKey:#"title"];
return self;
}
I'm guessing that your dictionary doesn't contain a "location", and that's consistent with what I see coming back from that web site. It sends back an array of dictionaries which contain arrays of dictionaries. You need to extract one of those inner dictionaries to find a "location".
[
{
"date":1320883200000,
"events":[
{
"affectedDate":1320883200000,
"event":{
"appId":620,
"eventId":20672,
"location":"Samsen Kulturhus",
"municipality":"Kristiansand",
"title":"AKKS kurs høsten 2011"
}
},
....
Try:
- (id)initWithDictionary:(NSDictionary*) dict {
self = [super init];
if(self) {
self.date = [dict valueForKey:#"date"];
self.location = [dict valueForKey:#"location"];
self.municipality = [dict valueForKey:#"municipality"];
self.title = [dict valueForKey:#"title"];
}
return self;
}