Get only last vale of dictionary [closed] - ios

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am new in iOS development and my problem is when i parse data than only last value is showing above value are not showing .Please solve my issue.
Array name city info get 3 value but when i want to display them it gives onle last value of array.
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:WebData1 options:0 error:0];
NSArray *city_info = [json objectForKey:#"city_info"];
for(NSDictionary *dic in city_info) {
NSMutableArray *vlcc_service_name = [dic objectForKey:#"vlcc_service_name"];
Centers = [[NSMutableArray alloc]initWithObjects:vlcc_service_name, nil];
}
// NSLog(#"%#", vlcc_service_name);
NSLog(#"%#", Centers);
[_CenterTableView reloadData];
}

NSDictionaries are unordered,that there are not first or last element. In fact, the order of the keys are never guaranteed to be the same, even in the lifetime of a specific dictionary.
If you want any object, you can get one of the keys:
id key = [[json allKeys] objectAtIndex:0]; // ensure that your 'json' is not empty
id object = [json objectForKey:key];
Choice - 2
array you can get all objects
Centers = [NSMutableArray new]; // allocate the memory on outside the Loop
for(NSDictionary *dic in city_info) {
[Centers addObject: [dic objectForKey:#"vlcc_service_name"]];
}
NSLog(#"the last object=%#", [Centers lastObject]);
// else
NSLog(#"the last object=%#", [yourArray objectAtIndex:[Centers count] - 1]; );

Please try with this.
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:WebData1 options:0 error:0];
NSArray *city_info = [json objectForKey:#"city_info"];
NSMutableArray *Centers = [[NSMutableArray alloc]init];
for(NSDictionary *dic in city_info) {
NSString *vlcc_service_name = [dic objectForKey:#"vlcc_service_name"];
/NSLog(#"%#", vlcc_service_name);
[Centers addObject: vlcc_service_name];
}
NSLog(#"%#", Centers);
[_CenterTableView reloadData];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:WebData1 options:0 error:0];
NSArray *city_info = [json objectForKey:#"city_info"];
NSMutableArray *Centers = [NSMutableArray array];
for(NSDictionary *dic in city_info) {
NSMutableArray *vlcc_service_name = [dic objectForKey:#"vlcc_service_name"];
[Centers addObjectsFromArray:vlcc_service_name];
}
// NSLog(#"%#", vlcc_service_name);
NSLog(#"%#", Centers);
[_CenterTableView reloadData];
}

You can do it without any for loop. Do like this:
NSMutableArray *Centers = [[NSMutableArray alloc]initwithArray:city_info];

Related

Building NSMutableArray from NSMutableDictionary resulting in NSException

I am a newbie in iOS development. I was trying to put the results of an NSMutableArray into an NSMutableString but this is resulting in an NSException.
Here is my code:
NSMutableArray *oldtableData = .......this is where I recieve card data;
NSError *error;
NSMutableData *tableDataUpdated = [[NSJSONSerialization dataWithJSONObject:oldtableData
options:0
error:&error] copy];
NSMutableDictionary *cardDictionary = [NSJSONSerialization JSONObjectWithData:tableDataUpdated options:0 error:NULL];
For converting the cardDictionary into a NSMutableArray, I am using this piece of code (which is giving me an NSException)
NSMutableArray *type = [NSMutableArray array];
NSMutableArray *last4Digits = [NSMutableArray array];
[cardDictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
[type addObject:[obj valueForKeyPath:#"type"]];
[last4Digits addObject:[obj valueForKeyPath:#"last4Digits"]];
}];
But If I exclude the above code and try NSLog with this piece of code
NSLog(#"JSON: %#",cardDictionary);
Console will give a proper json result; something like this:
JSON: (
{
cardPciId = "###########";
fingerPrint = ###########;
last4Digits = 4321;
type = Mastercard;
},
{
cardPciId = "###########";
fingerPrint = ###########;
last4Digits = 1234;
type = Visa;
}
)
I am trying to convert this into two Arrays, one with all the "type"s and another one with all "last4Digits". But this is what I get
Uncaught exception: -[__NSCFArray enumerateKeysAndObjectsUsingBlock:]:
unrecognized selector sent to instance 0x7ff7060badf0
I tried to hover through StackOverFlow to find a solution but none of them seem to be working. :(
It looks like cardDictionary is actually an NSArray instance containing the dictionaries. So, you should iterate through the array, and get type and last4Digits from each dictionary using objectForKey instead of valueForKeyPath:
NSArray *cardDictionaries = [NSJSONSerialization JSONObjectWithData:tableDataUpdated options:0 error:NULL];
NSMutableArray *type = [NSMutableArray array];
NSMutableArray *last4Digits = [NSMutableArray array];
[cardDictionaries enumerateObjectsUsingBlock:^(NSDictionary *cardDictionary, NSUInteger idx, BOOL *stop) {
[type addObject:[cardDictionary objectForKey:#"type"]];
[last4Digits addObject:[cardDictionary objectForKey:#"last4Digits"]];
}];
There is a lot going on here, but I want to point one thing out.
Table data is being serialized to JSON.
NSMutableData *tableDataUpdated = [[NSJSONSerialization dataWithJSONObject:oldtableData
options:0
error:&error] copy];
Next, the data that was just serialized is de-serialized. It will always be the same array.
NSMutableDictionary *cardDictionary = [NSJSONSerialization JSONObjectWithData:tableDataUpdated options:0 error:NULL];
You will always get the same data back. You don't need to do the JSON step at all.

Mapping JSON response field into NSArray

Response:
{"rsBody":
[{"productId":11,
"productImageUrl":"http:xxxx"},
{"productId":9,
"productImageUrl":"http:"xxxx"}]}
I know this is a repeated question, but still asking cause not getting the right way to do it. I am getting some response from php server as JSON in an array which consists two objects. I want to map the element of both objects productImageUrl in an NSArray. Resultant array should be somewhat like
NSArray =[{#"url":"productImageUrl1"},{#"url":#"ProductImageUrl2"}, nil];
productImageUrl1 = element of 1st object, productImageUrl2 = element of 2nd object.
I am parsing the response and able to to extract it from rsBody.
NSDictionary* response=(NSDictionary*)[NSJSONSerialization
JSONObjectWithData:receivedData options:kNilOptions error:&tempError];
NSArray *rsBody = [response objectForKey:#"rsBody"];
Try this:
NSMutableArray *arr = [[NSMutableArray alloc] init];
NSDictionary* response = [NSJSONSerialization JSONObjectWithData:receivedData options:kNilOptions error:&tempError];
NSArray *rsBody = [response objectForKey:#"rsBody"];
for (NSDictionary *dict in rsBody)
{
NSMutableDictionary *dictURL = [[NSMutableDictionary alloc] init];
[dictURL setValue:[dict valueForKey:#"productImageUrl"] forKey:#"url"];
[arr addObject:dictURL];
}
NSLog(#"%#", arr);

How to Add An array into Array index by index in iOS?

i am newBie in iOS Development. i want to add my JSON Parsing Data Dictionary Array Key Value in to another array But it only Add My Last Array index in to New Array.
My Code like as
-(void)fetchedData:(NSData *)responsedata
{
if (responsedata.length > 0)
{
NSError* error;
self.json = [NSJSONSerialization JSONObjectWithData:responsedata options:kNilOptions error:&error];
if ([[_json objectForKey:#"data"] isKindOfClass:[NSArray class]])
{
NSArray *arr = (NSArray *)[_json objectForKey:#"data"];
[self.imageArray addObjectsFromArray:arr];
[self.storeViewTable reloadData];
}
self.storeViewTable.hidden=FALSE;
}
NSMutableArray *imagearray=[[NSMutableArray alloc]init];
for (index=0; index <[self.imageArray count]; index ++)
{
for(NSDictionary *dict in self.imageArray )
{
imagearray = [dict valueForKey:#"demopage"];
self.imagesa = imagearray;
}
}
NSLog(#"Array Count %d",[self.imagesa count]);
NSLog(#"Another array Count %d",[self.imageArray count]);
}
Here self.imagearray is my main array that contain my all JSON Data but i want to Parse A new Data From old Data And add it in to self.imagesa array here For self-images Value for key is demo page and Self.imagearray count is Three(3) So i want all my Three Index value in to self.imagesa but it contain only Last index Value please Give me Solution For that.And my Webservices link is Here. link
your code should look like below.
id json = [NSJSONSerialization JSONObjectWithData:responsedata options:kNilOptions error:&error];
if ([[json objectForKey:#"data"] isKindOfClass:[NSArray class]])
{
NSArray *arr = (NSArray *)[json objectForKey:#"data"];
[imageArray addObjectsFromArray:arr];
}
//do not alloc init if you have already alloc init array.
NSMutableArray *imagesa=[[NSMutableArray alloc]init];
for(NSDictionary *dict in imageArray )
{
[imagesa addObject:#{#"demopage":[dict valueForKey:#"demopage"]}];
}
NSLog(#"Array Count %lu",(unsigned long)[imagesa count]);
NSLog(#"Another array Count %lu",(unsigned long)[imageArray count]);
and i got below output
Array Count 3
Another array Count 3
NOTE
and if you want to add all demopage dictionary to imagesa array then replace your for loop
for(NSDictionary *dict in imageArray )
{
NSArray *arr = (NSArray *)[dict valueForKey:#"demopage"];
[imagesa addObjectsFromArray:arr];
}
and output is
Array Count 69
Another array Count 3

How to get array of values from NSDictionary array

When I try to print array of json values in log, I get addresses instead of values. Here's how I coded.
NSData *jsonData = [json dataUsingEncoding:NSASCIIStringEncoding];
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
NSMutableArray *tempArray = [NSMutableArray arrayWithCapacity:jsonArray.count];
NSMutableArray *anotherTempArray = [NSMutableArray arrayWithCapacity:jsonArray.count];
NSDictionary *dict;
for(dict in jsonArray)
{
NSString *projectName = dict[#"Name"];
NSString *urlText = dict[#"Url"];
NSLog(#"Url text in array = %#", urlText);
NSString *attch = dict[#"attachmentes"];
NSLog(#"Attached url in array = %#", attch);
NSString *projID = dict[#"ProjectID"];
NSLog(#"Project ID in array = %#", projID);
SaveAttachment *saveAt = [[SaveAttachment alloc] initWithName:projectName withList:#"View" withAttachment:#"View"];
[tempArray addObject:saveAt];
SaveProjectId *saveProj = [[SaveProjectId alloc] initWithProjectId:projID];
saveProj.projectId = projID;
[anotherTempArray addObject:saveProj];
}
array = tempArray;
[self.tableViewProject reloadData];
NSLog(#"Array of project IDs === %#", anotherTempArray); //Get values (array of project ids here.
}
Replace
SaveProjectId *saveProj = [[SaveProjectId alloc] initWithProjectId:projID];
saveProj.projectId = projID;
[anotherTempArray addObject:saveProj];
with
[anotherTempArray addObject:projID];
This is because your anotherTempArray contains objects of SaveProjectId ie, everytime in for loop you are adding saveProj object not projID. Thats why your array showing SaveProjectId objects.
If you want to directly save them, then use the below modification
[anotherTempArray addObject:projID];
or you can use like(this is i would prefer)
NSLog(#"First project ID === %#", [anotherTempArray objectAtindex:0] projectId]);
You are storing SaveProjectId objects in the array, therefore when you print the content you see the address of those objects.
your "anotherTemoArray" is having objects of SaveProbectId so you have to pass object at index to SaveProjectId and then you can see the array information
When calling NSLog(#"Array of project IDs === %#", anotherTempArray); the -(NSString*)description method on each of the objects inside 'anotherTempArray' is being called.
In your case that means -(NSString*)description is being called on SaveProjectId objects. Override it to print out what you want... e.g.
-(NSString*)description {
return [NSString stringWithFormat:#"SaveProjectId: %#",self.projectId];
}

how to add JSON data to an NSArray

I have json data as below.
[
{"id":"2","imagePath":"image002.jpg","enDesc":"Nice Image 2"},
{"id":"1","imagePath":"image001.jpg","enDesc":"Nice Image 1"}
]
I am assigning this to variable named NSArray *news.
Now I have three different array as below.
NSArray *idArray;
NSArray *pathArray;
NSArray *descArray;
I want to assign data of news to these arrays so that finally I should have as below.
NSArray *idArray = #["2","1"];
NSArray *pathArray = #["image002.jpg","image001.jpg"];
NSArray *descArray = #["Nice Image 2","Nice Image 1"];
Any idea how to get this done?
With the help of below answer this is what I did.
pathArray = [[NSArray alloc] initWithArray:[news valueForKey:#"imagePath"]];
I don't wanted to use NSMutableArray for some reasons.
You should use JSONKit or TouchJSON to convert your JSON data to Dictionary.
Than you may do this :
NSArray *idArray = [dictionary valueForKeyPath:#"id"]; // KVO
Use this
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:receivedData options:NSJSONReadingMutableContainers error:nil];
then you can extract all the information that you need from there you have NSArray that contains NSDictionary , where you can go and use objectForKey: to get all the info you need.
Load the json data into an NSDictionary, which you may call "news" . Then retrieve as
NSArray *idArray = [news valueForKeyPath:#"id"];
NSArray *pathArray = [news valueForKeyPath:#"imagePath"];
NSArray *descArray = [news valueForKeyPath:#"enDesc"];
Yes all the above ans is correct I am just integrating all of them together to be easly use to you:
NSArray *serverResponseArray = [NSJSONSerialization JSONObjectWithData:receivedData options:NSJSONReadingMutableContainers error:nil]; // I am assigning this json object to an array because as i show it is in array format.
now:
NSArray *idArray = [[NSMutableArray alloc] init];
NSArray *pathArray = [[NSMutableArray alloc] init];
NSArray *descArray = [[NSMutableArray alloc] init];
for(NSDictionary *news in serverResponseArray)
{
[idArray addObject:[news valueForKey:#"id"]];
[pathArray addObject:[news valueForKey:#"imagePath"]];
[descArray addObject:[news valueForKey:#"enDesc"]];
}

Resources