How to get the no. of objects in JSON Data? - ios

If i am saving my data in NSDictionary "dict"
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableLeaves error:nil];
How can i know that how many objects i am having in seasons, i know how to save NSArray and it's count but it's not an array actually. and all question i saw on stackoverflow they all are using array object.
{ "seasons":{
"Season 0":{ },
"Season 1":{ }
}

NSDictionary has a count method:
NSInteger count = [dict[#"seasons"] count]; // Returns 2

Try This It will give the array of values / keys
[dict allValues]; or [dict allKeys]

Related

Mutating method sent to immutable object error when removing object

I want to remove object from array but I am getting this error. I found relative questions but not able to get.
please help me.
my code is
NSArray *tripsArray= [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSMutableArray *myTripsArray = [tripsArray mutableCopy];
for (NSDictionary *dict in myTripsArray){
if ([[dict valueForKey:#"state"] isEqualToString:#"undeployed"]){
int index = [myTripsArray indexOfObject:dict];
[myTripsArray removeObjectAtIndex:index];
}
}
This is due to the array which you are iterating, you are removing an object from the same array.
Change this line:
for (NSDictionary *dict in myTripsArray)
To this:
for (NSDictionary *dict in [myTripsArray copy])
Here I used the copy of the array to iterate and used the original one to mutate.
Try doing this:
NSArray *tripsArray = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSMutableArray *myTripsArray = [tripsArray mutableCopy];
for (NSDictionary *dict in [myTripsArray copy]){
if ([[dict valueForKey:#"state"] isEqualToString:#"undeployed"]){
int index = [myTripsArray indexOfObject:dict];
[myTripsArray removeObjectAtIndex:index];
}
}
// And now myTripsArray will be changed
You got the error because you tried to change an array in enumerating time. You should make copy of this array and use one array for enumerating and second for removing. Or you can add all items for removing (which you will find in cicle) in second array and then just remove them by call removeObject:.
Don't store indexes cause after first remove second index can be wrong (if second object has higher index than first).

Convert Array of Dictionary in single Array

This code:
server_response = [{id:1},{id:2},{id:3},{id:4}]
I am getting above response from server now I want only the list of ids in one array like
ids = [1,2,3,4];
I know we can do by for loop but it takes long time if thousand of ids inside the response array.
Is there any better way to achieve above equation?
NSArray *result = [yourArray valueForKey:#"id"]
From the documentation for NSArray instance method valueForKey:
Returns an array containing the results of invoking valueForKey: using key on each of the array's objects
NSMutableArray *resultArray = [NSMutableArray array];
for (NSDictionary *dict in server_response) {
[resultArray addObject:[dict objectForKey:#"id"]];
}
Try above code. Hope it will help you. Result array has final values
NSArray *server_response = #[#{#"id":#"1"},#{#"id":#"2"},#{#"id":#"3"},#{#"id":#"4"}];
NSMutableArray *resultArray = [NSMutableArray array];
NSString *birdtemp;
for (NSDictionary *object in server_response) {
birdtemp = object[#"id"];
[resultArray addObject:birdtemp];
}
NSLog(#"%#",resultArray);
OutPut: [
1,
2,
3,
4
]

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 parse a Nested JSON

Thank you reading my post, I known this topic was asked so many time, and I had saw that but no luck...
I want to parse a simple JSON string, as followings:
[
{
"id":"1",
"name_en":"Photography",
"subchannels":[
{
"id":"4",
"name_en":"John"
},
{
"id":"18",
"name_en":"Sam"
}
]
},
{
"id":"7",
"name_en":"Equipment",
"subchannels":[
{
"id":"25",
"name_en":"ABC Company"
},
{
"id":"40",
"name_en":"CDE Company"
}
]
}
]
It had convert this string to NSDictionary
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *testDic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&e];
Then I list the Dictionary Key
for(id key in testDic) {
NSLog(#"%#", key);
}
The result is the entire record as the Dictionary Key, so I can't use [testDic objectForKey:key] to retrieve the value.
How can I get the first row name_en and the second row subchannels value?
(is it possible to retrieve easily like xpath in XML?)
Thank you for helping.
First of all. The root object of your model is NSArray object - not `NSDictionary. '[]' means array and {} means dictionary.
NSArray *dataArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&e];
for (NSDictionary *entry in dataArray) {
NSString *name = entry[#"name_en"];
NSArray *subchannels = entry[#"subchannels"]; //array of dictionaries
NSLog(#"Name %s", name);
for (NSDictionary *subchannel in subchannels) {
NSLog(#"Subchannels name %# id: %d", subchannel[#"name"], [subchannel[#"id"] integerValue]);
}
}
If you want to perform advances JSON parsing I encourage you to look at Mantle github project.

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

Resources