How to copy custom NSObject into NSMutableArray - ios5

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

Related

Split array into three separate arrays

I have an array and I want to split that array into 3 parts or 3 arrays.
1st array contains -> AppName
2nd array contains -> Description
3rd array contains -> Icon
Here is the json array I want to split,
Deviceinfo = (
{
Appname = App;
Description = "This is test app";
Icon = "57.png";
}
);
}
Here is my code for this,
NSMutableArray *firstArray = [NSMutableArray array];
NSMutableArray *secondArray = [NSMutableArray array];
NSMutableArray *thirdArray = [NSMutableArray array];
for (int i = 0; i < [json count]; i++) {
NSArray *tempArray = [[json objectAtIndex:i]componentsSeparatedByString:#""];
[firstArray addObject:[tempArray objectAtIndex:0]];
[secondArray addObject:[tempArray objectAtIndex:1]];
if ([tempArray count] == 3)
{
[thirdArray addObject:[tempArray objectAtIndex:2]];
}
}
NSLog(#"yourArray: %#\nfirst: %#\nsecond: %#\nthird: %#", json, firstArray, secondArray, thirdArray);
I observe a crash in the code at this line,
NSArray *tempArray = [[json objectAtIndex:i]componentsSeparatedByString:#""];
I don't understand what is going wrong here. Any pointers to solve this issue?
I think you can using below code i hope this help's you :-
NSMutableArray *firstArray = [NSMutableArray array];
NSMutableArray *secondArray = [NSMutableArray array];
NSMutableArray *thirdArray = [NSMutableArray array];
NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData: jsonResponse options: NSJSONReadingMutableContainers error: &e];
//here is first i load with Dicutionary bcz if into your Json you have may be multiple Dictuionary so you then you can load purticular dictionary as bellow line
EDIT
NSArray * responseArr = jsonArray[#"Deviceinfo"];
firstArray = [responseArr valueForKey:#"Appname"];
secondArray = [responseArr valueForKey:#"Description"];
thirdArray = [responseArr valueForKey:#"Icon"];
if you have multiple Deviceinfo dictionary in to your Json then you could use For loop
// NSArray * responseArr = jsonArray[#"Deviceinfo"];
// for (NSDictionary *dict in responseArr) {
// [firstArray addObject:[dict valueForKey:#"Appname"];
// [secondArray addObject:[dict valueForKey:#"Description"];
// [thirdArray addObject:[dict valueForKey:#"Icon"];
// }
NSMutableArray *firstArray = [[NSMutableArray alloc]init];
NSMutableArray *secondArray = [[NSMutableArray alloc]init];
NSMutableArray *thirdArray = [[NSMutableArray alloc]init];
NSDictionary *list =[NSJSONSerialization JSONObjectWithData:data
options:kNilOptions error:&error];
NSArray * tempArray = jsonArray[#"Deviceinfo"];
for (NSDictionary *list in tempArray)
{
[firstArray addObject:[list objectForKey:#"Appname"];
[secondArray addObject:[list objectForKey:#"Description"];
[thirdArray addObject:[list objectForKey:#"Icon"];
}
Then try
NSLog(#"yourArray: %#\nfirst: %#\nsecond: %#\nthird: %#", tempArray, firstArray, secondArray, thirdArray);
NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://url.to.your.json"]];
NSArray *jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
NSMutableArray *appNameArray = [NSMutableArray array];
NSMutableArray *discriptionArray = [NSMutableArray array];
NSMutableArray *iconArray = [NSMutableArray array];
for(NSDictionary *dictionary in jsonObjects)
{
[appNameArray adddObject:[dictionary valueForKey:#"Appname"];
[appNameArray adddObject:[dictionary valueForKey:#"Description"];
[appNameArray adddObject:[dictionary valueForKey:#"Icon"];
}

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.

exc_breakpoint while JSON parsing

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);
}
}

JSON array for picker view iPhone

I am getting this data from JSON web services
List ARRAY: (
{
assets = (
{
identity = 34DL3611;
systemId = 544507;
},
{
identity = 34GF0512;
systemId = 5290211;
},
{
identity = 34HH1734;
systemId = 111463609;
},
{
identity = 34HH1736;
systemId = 111463622;
},
{
identity = 34YCJ15;
systemId = 294151155;
}
);
identity = DEMO;
systemId = 4921244;
})
By using this code:
NSArray *list =[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"Response data: %#", responseString);
NSLog(#"List ARRAY: %#", list);
NSDictionary *dict = [list objectAtIndex: 0];
NSMutableArray *vehicleGroups = [dict objectForKey:#"identity"];
NSLog(#"Vehicle Groups: %#", vehicleGroups);
Here is the picker code I am using:
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
return 1;}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent :(NSInteger)component {
return [vehicleGroups count];}
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{return nil;}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
}
The application crashes at the line
return [vehicleGroups count];
delegate method numberOfRowsInComponent of pickerView. I am not getting that - why I am facing this issue?
//Code////
NSArray *list =[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"Response data: %#", responseString);
NSLog(#"List ARRAY: %#", list);
NSDictionary *dict = [list objectAtIndex: 0];
vehicleList = [dict objectForKey: #"assets"];
self.vehicleGroups = [[NSMutableArray alloc] init];
vehicleGroups = [dict objectForKey:#"identity"];
NSLog(#"Vehicle Groups: %#", vehicleGroups);
NSString *identity = [dict objectForKey: #"identity"];
NSString *systemid = [dict objectForKey:#"systemId"];
self.listVehicles = [[NSMutableArray alloc] init];
self.listVehiclesID =[[NSMutableArray alloc]init];
NSLog(#"GroupOfVehicles: %#", groupOfVehicles);
for (NSUInteger index = 0; index < [vehicleList count]; index++) {
itemDict = [vehicleList objectAtIndex: index];
[self.listVehicles addObject:[itemDict objectForKey:#"identity"]];
[self.listVehiclesID addObject:[itemDict objectForKey:#"systemId"]];
}
NSLog(#"Group Name: %#", identity);
NSLog(#"Assets: %#", listVehicles);
NSLog(#"Assets System ID: %#", listVehiclesID);
NSLog(#"GroupSystemID: %#", systemid);
You have to initialise your array first
NSDict *list =[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"List Dict: %#", list);
NSMutableArray *temp = list[#"assets"];
NSMutableArray *vehicleGroups = [NSMutableArry array];
vehicleGroups = temp[0][#"identity"];
NSLog(#"Vehicle Groups: %#", vehicleGroups);
Answering my own question guide others if they face the same problem, Actually what I have done here to get the required array for identity: DEMO is as follows:
vehicleGroups =[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"Response data: %#", responseString);
NSLog(#"List ARRAY: %#", vehicleGroups);
NSDictionary *dict1 = [vehicleGroups objectAtIndex: 0];
NSString *identity1 = [dict objectForKey: #"identity"];
NSLog(#"dictNEW: %#", dict1);
groupOfVehicles = [[NSMutableArray alloc] init];
for (NSUInteger index = 0; index < [vehicleGroups count]; index++) {
itemDict = [vehicleGroups objectAtIndex: index];
[groupOfVehicles addObject:[itemDict objectForKey:#"identity"]];
}
NSLog(#"Group Name NEW: %#", identity1);
NSLog(#"Groups NEW: %#", groupOfVehicles);
After using that code I have properly got the array for my required data
retain the array as
[vehicleGroups retain] after vehicleGroups = [dict objectForKey:#"identity"];
NSDictionary *dicts = [list objectAtIndex: 0];
NSMutableArray *vehicleGroups = [[NSMutableArray alloc] init];
for (NSDictionary *dict in dicts)
{
NSString* identity = [dict objectForKey:#"identity"];
[vehicleGroups addObject:identity];
}
NSLog("count is %d",[vehicleGroups count]);
have a try :)
Your JSON data is not JSON.
{
"assets" : [
{
"identity" : "34DL3611",
"systemId" : 544507
},
....
{
"identity" = "34YCJ15",
"systemId" = 294151155
}
],
"identity" = "DEMO",
"systemId" = 4921244
}
This is a possible example of your data was it described in JSON.
NSDictionary *dict = [list objectAtIndex: 0];
NSMutableArray *vehicleGroups = [dict objectForKey:#"identity"];
It looks to me like dict here is a dictionary with three entries: assets, identity, and systemId. At this level, the value of identity is just a string, "DEMO", but you're trying to assign it to a mutable array. I think you want something like this instead:
NSDictionary *dict = [list objectAtIndex: 0];
NSArray *assets = [dict objectForKey:#"assets"];
NSArray *vehicleGroups = [assets objectForKey:#"identity"];
(It's okay to send -objectForKey: to an array -- you get back an array of objects corresponding to the given key for each object in the receiver.)

displaying JSON data in Tableview in iphone

below is the JSON i want to parse it in such a way that for e.g date 1st should all events in that section of table and 2nd date should show all related events in another section
I am parsing using below code but i am not getting required sequence
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];
appDelegate.books1 = [[NSMutableArray alloc] init];
appDelegate.dates =[[NSMutableArray alloc]init];
for (int j=0;j<10; j++) {
NSDictionary *dictOne = [results objectAtIndex:j];
NSLog(#"%# - %#", [dictOne objectForKey:#"date"]);
Date *aDate = [[Date alloc] initWithDictionary:[results objectAtIndex:j]];
[appDelegate.dates addObject:aDate];
[aDate release];
}
for (int i=0; i<10; i++) {
NSDictionary *dictOne = [results objectAtIndex:i];
NSArray *activitiesArray = [dictOne objectForKey:#"events"];
NSDictionary *dictTwo = [activitiesArray objectAtIndex:i];
NSDictionary *eventDict=[dictTwo objectForKey:#"event"];
// NSLog(#"%# - %#", [dictOne objectForKey:#"date"]);
// NSLog(#"%# - %#", [dictTwo objectForKey:#"affectedDate"]);
// NSLog(#"%# - %#", [eventDict objectForKey:#"location"]);
NSInteger*date=[dictOne objectForKey:#"date"];
NSInteger*affectedDate=[dictTwo objectForKey:#"affectedDate"];
NSString*appId =[eventDict objectForKey:#"appId"];
NSString*eventId=[eventDict objectForKey:#"eventId"];
NSString*location=[eventDict objectForKey:#"location"];
NSString*municipality=[eventDict objectForKey:#"municipality"];
NSString*title=[eventDict objectForKey:#"title"];
Book1 *aBook=[[Book1 alloc] initWithDate:date affectedDate:affectedDate location:location municipality:municipality title:title];
[appDelegate.books1 addObject:aBook];
int count=[appDelegate.books1 count];
}
the json format is given below
http://www.krsconnect.no/community/api.html?method=bareListEventsByCategory&appid=620&category-selected=350&counties-selected=Vest-Agder,Aust-Agder
You need to aggregate your data in some different way.
Here is how I'd do that:
...
// why do you parse your json string two times?
//NSDictionary *object = [parser objectWithString:json_string error:nil];
NSArray *results = [parser objectWithString:json_string error:nil];
// You have memory leak here. I assume that books1 and dates are both properties with "retain" flag set.
//appDelegate.books1 = [[NSMutableArray alloc] init];
//appDelegate.dates =[[NSMutableArray alloc]init];
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]];
}
}
}
}
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tblView {
return [data count];
}
- (NSInteger) tableView:(UITableView *)tblView numberOfRowsInSection:(NSInteger)section {
return [[[data objectAtIndex:section] objectForKey:#"rows"] count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return [[data objectAtIndex:section] objectForKey:#"section"];
}
- (UITableViewCell *) tableView:(UITableView *)tblView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellID = #"DefaultCell";
UITableViewCell *cell = (UITableViewCell *)[tblView dequeueReusableCellWithIdentifier:cellID];
if ( cell == nil ) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID] autorelease];
}
cell.textLabel.text = [[[data objectAtIndex:indexPath.section] objectForKey:#"rows"] objectAtIndex:indexPath.row];
return cell;
}