JSON array for picker view iPhone - 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.)

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.

how can print array json values into uitableview in iphone

JSON format code looks like this:
{
"rates": {
"amc": "201",
"hyd": "500.50",
"guj": "200.10",
"afgd": "400"
}
}
After parsing JSON values the above code array returns:
array = [values valueForKey:#"rates"];
which array return
{
amc = "201";
hyd = "500.50";
guj = "200.10";
afgd = "400";
...........etc
}
But i want to print in UITableView look amc:201
How can i do this?
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
self.responseData = nil;
values = [responseString JSONValue];
array = [[NSMutableArray alloc] init];
NSMutableArray *arrTitle = [[NSMutableArray alloc] init];
NSMutableArray *arrValues = [[NSMutableArray alloc] init];
array =[values valueForKey:#"rates"];
NSLog(#"array values:--> %#",array);
// NSLog(#"values:--> %#",values);
// NSLog(#"Particular values:--> %#",[[values valueForKey:#"rates"] valueForKey:#"AED"]);
tempDict1 = (NSMutableDictionary *)array;
NSArray *arr;// =[[NSArray alloc]init];
arr = [[tempDict1 valueForKey:#"rates"] componentsSeparatedByString:#";"];
NSLog(#"arr-->%#",arr);
NSString *subStar = #"=";
[arrTitle removeAllObjects];
[arrValues removeAllObjects];
for (int i=0; i<[arr count]-1; i++)
{
[arrTitle addObject:[[arr objectAtIndex:i] substringToIndex:NSMaxRange([[arr objectAtIndex:i] rangeOfString:subStar])-1]];
[arrValues addObject:[[arr objectAtIndex:i] substringFromIndex:NSMaxRange([[arr objectAtIndex:i] rangeOfString:subStar])]];
NSLog(#"arrTitle is:--> %#",arrTitle);
}
tempDict1 = (NSMutableDictionary*)[array objectAtIndex:0];
array = [values valueForKey:#"rates"];
NSLog(#"tempDict--%#",[tempDict1 objectForKey:#"AED"]);
[array retain];
[tbl_withData reloadData];
}
try:
NSMutableArray * array2=[[NSMutableArray alloc]init];
[array addObject: [[array objectAtIndex:0] objectForKey:#"amc"]];
[array addObject: [[array objectAtIndex:0] objectForKey:#"hyd"]];
[array addObject: [[array objectAtIndex:0] objectForKey:#"guj"]];
[array addObject: [[array objectAtIndex:0] objectForKey:#"afgd"]];
now put array2 values in your table cell.
like:
cell.text=[array2 objectAtIndex:indexPath.row];
try this:-
NSDictionary *dict =[values valueForKey:#"rates"];
NSString *str=[dict valueForKey:#"amc"];
You need to do this:-
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
self.responseData = nil;
values = [responseString JSONValue];
NSMutableArray *arrTitle = [[NSMutableArray alloc] init];
NSMutableArray *arrValues = [[NSMutableArray alloc] init];
NSDictionary *dict =[values valueForKey:#"rates"];
NSString *str=[dict valueForKey:#"amc"];
rest you can do according to your requirements.
Return type for [values valueForKey:#"rates"] is a dictionary not array of values.
NSDictionary *dict = [values valueForKey:#"rates"];
Now you can refer get values within dictionary using objectForKey
Or else if you want to store in array.
NSMutableArray *array = [NSMutableArray array];
for (NSString *key in [dict allKeys])
{
array = [dict objectForKey:key];
}
So finally array has all the values within dictionary.
// returns no of rows
-(NSInteger) tableView: (UITableView *) tableView numberOfRowsInSection: (NSInteger) section
{
return [array count];
}
// contents of row will be
-(UITableViewCell*) tableView: (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) indexPath
{
static NSString *CellIdentifier = #"test";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell...
NSString *value = [self. array objectAtIndex:indexPath.row];
cell.textLabel.text = value;
return cell;
}

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

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