I have dictionary:
{
6 = (
{
id = 6;
name = Andrea;
},
{
id = 6;
name = Paolo;
}
);
8 = (
{
id = 8;
name = Maria;
}
);
67 = (
{
id = 67;
name = Francesco;
},
{
id = 67;
name = Sara;
}
);
}
I tried to get Values to array.
My code is:
NSArray *arrayNew= [result valueForKey:#"67"];
NSLog(#"Hello:%#",arrayNew);
But Always i got null value.
My complete code:
NSMutableArray *idArray=[[NSMutableArray alloc]init];
NSString* path = [[NSBundle mainBundle] pathForResource:#"File"
ofType:#"txt"];
NSString* content = [NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:NULL];
NSMutableData *results11 = [content JSONValue];
NSLog(#"Check:%#",results11);
NSArray *array= [results11 valueForKeyPath:#"field"];
NSMutableDictionary* result = [NSMutableDictionary dictionary];
for (NSDictionary* dict in array)
{
NSNumber* anID = [dict objectForKey:#"id"];
if (![idArray containsObject:[dict objectForKey:#"id"]]) {
// do something
[idArray addObject:[dict objectForKey:#"id"]];
}
NSMutableArray* resultsForID = [result objectForKey:anID];
if (!resultsForID)
{
resultsForID = [NSMutableArray array];
[result setObject:resultsForID forKey:anID];
}
[resultsForID addObject:dict];
}
NSLog(#"Result:%#",result);
NSLog(#"ID arr:%#",idArray);
// NSArray *temp= [results11 valueForKeyPath:#"Response.alertHistory"];
NSString *arrayNew= [result valueForKeyPath:#"67"];
NSLog(#"Hello:%#",arrayNew);
File.txt : {
"field": [
{
"id": 6,
"name": "Andrea"
},
{
"id": 67,
"name": "Francesco"
},
{
"id": 8,
"name": "Maria"
},
{
"id": 6,
"name": "Paolo"
},
{
"id": 67,
"name": "Sara"
}
]
}
Finally with reference of Tommy's solution I solved my issue.
NSArray *commentArray = result[#67];
And my final code:
NSMutableArray *idArray=[[NSMutableArray alloc]init];
NSString* path = [[NSBundle mainBundle] pathForResource:#"File"
ofType:#"txt"];
NSString* content = [NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:NULL];
NSMutableData *results11 = [content JSONValue];
NSLog(#"Check:%#",results11);
NSArray *array= [results11 valueForKeyPath:#"field"];
NSMutableDictionary* result = [NSMutableDictionary dictionary];
for (NSDictionary* dict in array)
{
NSNumber* anID = [dict objectForKey:#"id"];
if (![idArray containsObject:[dict objectForKey:#"id"]]) {
// do something
[idArray addObject:[dict objectForKey:#"id"]];
}
NSMutableArray* resultsForID = [result objectForKey:anID];
if (!resultsForID)
{
resultsForID = [NSMutableArray array];
[result setObject:resultsForID forKey:anID];
}
[resultsForID addObject:dict];
}
NSLog(#"Result:%#",result);
NSMutableArray *arrayNew = [[NSMutableArray alloc] init];
for (int i=0; i<[idArray count]; i++) {
NSArray *commentArray = result[idArray[i]];
NSLog(#"COMM:%#",commentArray);
NSMutableArray *arr=[[NSMutableArray alloc]init];
for (NSDictionary* dict in commentArray)
{
[arr addObject:[dict objectForKey:#"name"]];
}
[arrayNew addObject:arr];
}
NSLog(#"ID arr:%#",idArray);
NSLog(#"Name arr:%#",arrayNew);
File.txt :
{
"field": [
{
"id": 6,
"name": "Andrea"
},
{
"id": 67,
"name": "Francesco"
},
{
"id": 8,
"name": "Maria"
},
{
"id": 6,
"name": "Paolo"
},
{
"id": 67,
"name": "Sara"
}
]
}
My final result:
ID arr:(
6,
67,
8
)
Name arr:(
(
Andrea,
Paolo
),
(
Francesco,
Sara
),
(
Maria
)
)
The most likely reason for this is that your NSDictionary uses integers, not NSStrings, as its keys. In this case this should work:
NSArray *arrayNew= [result objectForKey:#67]; // No quotes
NSMutableArray *arrayNew = [[NSMutableArray alloc] init];
NSArray *commentArray = [dictionary valueForKey:#"67"];
for (NSDictionary *commentDic in commentArray) {
Model *modelObj = [[Model alloc] init];
modelObj = [Model modelFromDictionary:commentDic];
[arrayNew addObject:modelObj]
}
Also you will have to create Model .h and .m class to do the mapping.
and modelFromDictionary method will do the mapping.
.m
#implementation Version
- (NSDictionary *)jsonMapping {
return [[NSDictionary alloc] initWithObjectsAndKeys:
#"id",#"id",
#"name",#"name",
nil];
}
+ (Model *)modelFromDictionary:(NSDictionary *)dictionary {
Model *model = [[Model alloc] init];
NSDictionary *mapping = [model jsonMapping];
for(NSString *attribute in [mapping allKeys]) {
NSString *classProperty = [mapping objectForKey:attribute];
NSString *attributeValue = [dictionary objectForKey:attribute];
if(attributeValue != nil && ![attributeValue isKindOfClass:[NSNull class]]) {
[model setValue:attributeValue
forKey:classProperty];
}
}
return model;
}
.h
#property (nonatomic, strong) NSString *id;
#property (nonatomic, strong) NSString *name;
+ (Model *)modelFromDictionary:(NSDictionary *)dictionary;
Related
{
distance = "0.03159804520191554";
rid = 374824705969;
uuid = "1838346268_374823983610_2016-08-08T07:32:08.679GMT";
},
{
rid = 374824705969;
uuid = "1838346268_374823983610_2016-08-08T07:32:08.679GMT";
},
{
rid = 374824706065;
uuid = "1838346268_374823983610_2016-08-08T07:32:22.680GMT";
}
This is what I got from the array of dictionaries. I want to remove duplicates where rid=374824705969 without using loops.Can any one help me.
Thanks in advance.
Try these one:
NSArray *array = #[
#{
#"rid" : #374824705969,
#"uuid" : #"1838346268_374823983610_2016-08-08T07:32:08.679GMT"
},
#{
#"rid" : #374824705969,
#"uuid" : #"1838346268_374823983610_2016-08-08T07:32:08.679GMT"
},
#{
#"rid" : #374824706065,
#"uuid" : #"1838346268_374823983610_2016-08-08T07:32:22.680GMT"
}];
NSMutableSet *keys = [NSMutableSet new];
NSMutableArray *result = [NSMutableArray new];
for (NSDictionary *data in array) {
NSString *key = data[#"rid"];
if ([keys containsObject:key]) {
continue;
}
[keys addObject:key];
[result addObject:data];
}
NSLog(#"%#", result);
I am newbie in iOS and i have an issue i parsed an array and show in table which having three sections and every each section i added new row to add up its all children in hierarchy but due to table reload issue its indexing change and show wrong results. here is my code below
+ (void)getTypesWith:(void (^)(NSArray *, NSError *))completionHandler
{
[ZNetworkManager postDataForBackGround:nil atURL:[ZMappingManager getRequestURLToGetPropertiesTypes] completionHandler:^(NSArray *array, NSError *error)
{
NSMutableArray *typesDictionariesArray =[NSMutableArray array];
NSMutableDictionary* details = [NSMutableDictionary dictionary];
if (!error)
{
NSDictionary *fetchedDictionary = (NSDictionary *) array;
if([fetchedDictionary isKindOfClass:[NSDictionary class]] == NO)
{
[details setValue:#"Fetched dictionary is null" forKey:#"desription"];
completionHandler(nil ,[NSError errorWithDomain:#"MyDomain" code:1 userInfo:details]);
}
else
{
if([[[fetchedDictionary objectForKey:#"meta"] objectForKey:#"status"] isEqualToString:#"200"]){
NSDictionary *data = [fetchedDictionary objectForKey:#"response"];
if([data isKindOfClass:[NSDictionary class]] == NO)
{
[details setValue:#"Fetched dictionary is null" forKey:#"desription"];
completionHandler(nil ,[NSError errorWithDomain:#"MyDomain" code:1 userInfo:details]);
}
else
{
NSArray *allTypes = [data objectForKey:#"type"];
if([allTypes count] == 0)
{
[details setValue:#"Fetched dictionary is null" forKey:#"desription"];
completionHandler(nil ,[NSError errorWithDomain:#"MyDomain" code:1 userInfo:details]);
}
else
{
NSMutableArray *searchTypes = [[NSMutableArray alloc] init];
for (int i=0; i<[allTypes count]; i++)
// for (NSDictionary *typeDic in allTypes)
{
NSDictionary *typeDic = [allTypes objectAtIndex:i];
[typesDictionariesArray addObject:typeDic];
ZZameenType *newType = [[ZZameenType alloc] init];
[newType loadFromDictionary:typeDic];
[searchTypes addObject:newType];
NSArray *arrayforChild = [typeDic objectForKey:#"childs"];
for (int j=0; j<[arrayforChild count]; j++)
// for(NSDictionary *typeChild in arrayforChild)
{
NSDictionary *typeChild = [arrayforChild objectAtIndex:j];
ZZameenType *newChild;
[typesDictionariesArray addObject:typeChild];
newChild = [[ZZameenType alloc] init];
[newChild loadFromDictionary:typeChild];
[searchTypes addObject:newChild];
if(j == 0)
{
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
NSString *combineString = [NSString stringWithFormat:#"All %#",[typeDic objectForKey:#"title_alt2"]];
[dict setObject:combineString forKey:#"title"];
[dict setObject:combineString forKey:#"title_alt2"];
[dict setObject:combineString forKey:#"title_alt1"];
[dict setObject:[typeDic objectForKey:#"type_id"] forKey:#"parent_id"];
[dict setObject:[typeDic objectForKey:#"child_list"] forKey:#"type_id"];
[typesDictionariesArray insertObject:dict atIndex:[typesDictionariesArray count]-1];
newChild = [[ZZameenType alloc] init];
[newChild loadFromDictionary:dict];
[searchTypes insertObject:newChild atIndex:[searchTypes count]-1];
}
}
newType = nil;
}
NSSortDescriptor *typeID_sort = [NSSortDescriptor sortDescriptorWithKey:#"type_id" ascending:YES];
[searchTypes sortUsingDescriptors:[NSArray arrayWithObjects:typeID_sort,nil]];
[ZGlobals saveSearchTypes:typesDictionariesArray];
completionHandler(searchTypes ,nil);
searchTypes = nil;
details = nil;
}
}
}else{
}
}
}
}];
}
cellForRowAtIndexPath
if(selectionC == nil) {
selectionC=[[[NSBundle mainBundle] loadNibNamed:#"SelectionCell" owner:self options:nil] objectAtIndex:0];
}
KLog(#"view frame is %#",NSStringFromCGRect(self.frame));
KLog(#"table frame is %#",NSStringFromCGRect(tableView.frame));
NSArray *values =[[ZGlobals getPropertTypeSectionsValues] objectAtIndex:indexPath.section];
ZZameenType *type =[values objectAtIndex:indexPath.row];
selectionC.selectionTitle.text = type.title;
selectionC.selectionTitle.textColor = [ZTheme cellValuesColorIPAD];
I'm trying to parse this JSON:
{
"GetMachineGroupsResult": {
"MachineGroups": [
{
"GroupCount": 1,
"GroupID": 101,
"GroupName": "Machine11"
},
{
"GroupCount": 6,
"GroupID": 201,
"GroupName": "Machine12"
},
{
"GroupCount": 1,
"GroupID": 301,
"GroupName": "Machine13"
},
{
"GroupCount": 1,
"GroupID": 501,
"GroupName": "Machine14"
},
{
"GroupCount": 7,
"GroupID": 701,
"GroupName": "Machine15"
},
{
"GroupCount": 1,
"GroupID": 901,
"GroupName": "Machine16"
},
{
"GroupCount": 1,
"GroupID": 1001,
"GroupName": "Machine17"
}
],
"Status": 0
}
}
Into an object created with attributes GroupCount, GroupID and GroupName.
Here is my code:
if (request.responseStatusCode >= 200 && request.responseStatusCode < 300)
{
NSData *responseData = [request responseData];
NSError* error;
NSDictionary* jsonOverview = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSString *resultStatusString = jsonOverview[#"GetMachineOverviewResult"][#"Status"];
int resultStatus = [resultStatusString intValue];
NSDictionary *parsedObject = jsonOverview[#"GetMachineGroupsResult"];
NSMutableArray *groups = [[NSMutableArray alloc] init];
NSArray *results = [parsedObject valueForKey:#"MachineGroups"];
NSLog(#"Count %lu", (unsigned long)results.count); //results.count = 7
for (NSDictionary *parseDic in results) {
MachineGroupList *machinegrouplist = [[MachineGroupList alloc] init];
NSLog(#"%#", [parseDic class]);
NSLog(#"%#", parseDic);
for (NSString *key in parseDic) {
if ([machinegrouplist respondsToSelector:NSSelectorFromString(key)]) {
[machinegrouplist setValue:[parseDic valueForKey:key] forKey:key];
}
[groups addObject:machinegrouplist];
}
}
NSLog (#"GroupObjects %lu", (unsigned long)[groups count]); //groups count = 21
For some reason, which I cannot fathom, it parses each item three times and I end up with 21 objects instead of 7. I know it will be something simple for one of the experts here but I am new to all this and would really appreciate a helping hand here, thanks.
Edit:
Thanks a lot, here is how it now looks and it works.. The addobject was in the wrong section!
for (NSDictionary *parseDic in results)
{
MachineGroupList *machinegrouplist = [[MachineGroupList alloc] init];
NSLog(#"%#", [parseDic class]);
NSLog(#"%#", parseDic);
for (NSString *key in parseDic)
{
if ([machinegrouplist respondsToSelector:NSSelectorFromString(key)])
{
[machinegrouplist setValue:[parseDic valueForKey:key] forKey:key];
}
//[groups addObject:machinegrouplist];
}
[groups addObject:machinegrouplist];
}
NSLog (#"GroupObjects %lu", (unsigned long)[groups count]); //groups count = 7
What's happening is the following. First, lets comment out some of the last lines of code so that it looks like this:
for (NSDictionary *parseDic in results) {
//MachineGroupList *machinegrouplist = [[MachineGroupList alloc] init];
NSLog(#"%#", [parseDic class]);
//NSLog(#"%#", parseDic);
//for (NSString *key in parseDic) {
// if ([machinegrouplist respondsToSelector:NSSelectorFromString(key)]) {
// [machinegrouplist setValue:[parseDic valueForKey:key] forKey:key];
// }
// [groups addObject:machinegrouplist];
//}
}
//NSLog (#"GroupObjects %lu", (unsigned long)[groups count]); //groups count = 21
You'll se that you're iterating over 7 dictionaries, each of which has 3 objects.
Now, comment out the previous NSLog, uncomment the the inner for loop and add a NSLog inside that loop to see what you're iterating on.
for (NSDictionary *parseDic in results) {
//MachineGroupList *machinegrouplist = [[MachineGroupList alloc] init];
//NSLog(#"%#", [parseDic class]);
//NSLog(#"%#", parseDic);
for (NSString *key in parseDic) {
// if ([machinegrouplist respondsToSelector:NSSelectorFromString(key)]) {
// [machinegrouplist setValue:[parseDic valueForKey:key] forKey:key];
// }
// [groups addObject:machinegrouplist];
NSLog(#"key: %#", key);
}
}
//NSLog (#"GroupObjects %lu", (unsigned long)[groups count]); //groups count = 21
You are iterating over the 3 objects of each of the 7 dictionaries and since you're adding each object to groups outside of if ([machinegrouplist respondsToSelector:NSSelectorFromString(key)]) you end up adding 21 to groups
Cheers.
Currently working on a way to create a new NSMutableDictionary from my returned JSON data. I want to extract: tide.tideSummary.data.type and tide.tideSummary.date.epoch - I want to create a new array of dictionaries but with these 2 keys.
Below is what I have now:
for (NSDictionary *dict in self.tideSummary) {
NSString *type = [self.tideSummary valueForKeyPath:#"data.type"];
NSString *date = [self.tideSummary valueForKeyPath:#"date.epoch"];
[sunCycleDictionary setValue:(type) forKey:#"type"];
[sunCycleDictionary setValue:(date) forKey:#"epoch"];
}
Right now my NSLog returns perfectly for each key. Sample log as of now, what is incorrect
epoch = (
1388724761,
1388746063,
...
My goal it to make this output: - an array of dictionaries.
{
type: Sunrise,
epoch: 1336116677
},
{
type: Sunset,
epoch: 1336116677
},
{
type: Moonset,
epoch: 1336116677
},
...
I think I am pretty close, I just need to join those 2 key value pairs in their own object. Do I need to create a NSMutableArray and addObject to the previously created dictionary?
Data I am working with:
"tideSummary": [
{
"date": {
"pretty": "11:58 AM PST on December 19, 2013",
...
"epoch": "1387483136"
},
"utcdate": {
"pretty": "7:58 PM GMT on December 19, 2013",
...
"epoch": "1387483136"
},
"data": {
"height": "5.97 ft",
"type": "High Tide"
}
},
Thoughts on how to make this happen?
You are very close to your output but the shown output is not fully Dictionary it is an array of Dictionaries, so you need to do something like this.
NSMutableArray *finalOutput = [[NSMutableArray alloc] init]; //Add this
for (NSDictionary *dict in self.tideSummary)
{
NSMutableDictionary *sunCycleDictionary = [[NSMutableDictionary alloc] init]; //Add this
NSString *type = [self.tideSummary valueForKeyPath:#"data.type"];
NSString *date = [self.tideSummary valueForKeyPath:#"date.epoch"];
[sunCycleDictionary setValue:(type) forKey:#"type"];
[sunCycleDictionary setValue:(date) forKey:#"epoch"];
[finalOutput addObject: sunCycleDictionary]; //Add this
}
NSLog(#"out of loop: %#", finalOutput);
Try this
NSMutableArray *outputArray = [[NSMutableArray alloc] init];
for (NSDictionary *dict in self.tideSummary)
{
NSMutableDictionary *sunCycleDictionary = [[NSMutableDictionary alloc] init];
NSString *type = [dict valueForKeyPath:#"data.type"];
NSString *date = [dict valueForKeyPath:#"date.epoch"];
[sunCycleDictionary setValue:(type) forKey:#"type"];
[sunCycleDictionary setValue:(date) forKey:#"epoch"];
[outputArray addObject:sunCycleDictionary];
}
NSLog(#"output array : %#", outputArray);
Try This
NSMutableArray *temp =[[NSMutableArray alloc]init];
for (NSDictionary *dict in self.tideSummary) {
NSString *type = [self.tideSummary valueForKeyPath:#"data.type"];
NSString *date = [self.tideSummary valueForKeyPath:#"date.epoch"];
NSLog(#"type: %#", type);
[sunCycleDictionary setValue:(type) forKey:#"type"];
[sunCycleDictionary setValue:(date) forKey:#"epoch"];
[temp addObject: sunCycleDictionary];
NSLog(#"in loop: %#", temp);
}
int i=0;
while (i<[_arayResjoBID count]) {
NSLog(#"%d",i);
NSDictionary *dict=[[NSMutableDictionary alloc]init];
[dict setValue:[[_arayResjoBID objectAtIndex:i]valueForKeyPath:#"BarCode"] forKey:#"barcode"];
[dict setValue:[[_arayResjoBID objectAtIndex:i] valueForKeyPath:#"ItemName"] forKey:#"itemname"];
[dict setValue:[[_arayResjoBID objectAtIndex:i] valueForKeyPath:#"Quantity"] forKey:#"quantity"];
[dict setValue:#"NO" forKey:#"Yes"];
[_arayFilter insertObject:dict atIndex:i];
i++;
}
}
NSLog(#"%#",_arayFilter);
[self.tableView reloadData];
OUTPUT: in debug area
(
{
Yes = NO;
barcode = 1002690094467;
itemname = "Box Oversized 100X80x80";
quantity = 5;
},
{
Yes = NO;
barcode = 1002690094474;
itemname = "Road Case Large";
quantity = 2;
},
{
Yes = NO;
barcode = 1002690094481;
itemname = "Road Case New Double";
quantity = 4;
}
)
How can I loop through this part of the json [{first set of values},{data->children->data->body} in objective c?
Json is
[
{
"kind": "Listing"
},
{
"kind": "Listing",
"data": {
"children": [
{
"data": {
"body": "body1"
}
},
{
"data": {
"body": "body2"
}
}
]
}
}
]
My current code is
m_ArrList=[[NSMutableArray alloc]init];
NSDictionary *infomation = [self dictionaryWithContentsOfJSONString:#"surveyquestion.json"];
NSArray *array=[infomation objectForKey:#"data"];
int ndx;
NSLog(#"%#",array);
for (ndx = 0; ndx < [array count]; ndx++) {
NSDictionary *stream = (NSDictionary *)[array objectAtIndex:ndx];
NSArray *string=[stream valueForKey:#"children"];
//i am stuck here
}
What do I do at the "//i am stuck here" ?
You might need to add the values of #"children" dictionary in an array and then parse that array to get the data inside children
[childrenArray addObject:[stream objectForKey:#"children"]];
// finally parse childrenArray
// You Just need to Implement following Lines and you will get all the data for Key Body in children array
NSDictionary *infomation = [self dictionaryWithContentsOfJSONString:#"surveyquestion.json"];
NSArray *string= [[infomation objectForKey:#"data"] objectForKey:#"children"];
[string enumerateObjectsUsingBlock:^(id obj, NSUInteger ind, BOOL *stop){
NSLog(#"Body : %#",[[obj objectForKey:#"data"] objectForKey:#"body"]);
}];
Using NSJSONSerialization try to implement this. Here you need to pass NSString as jsonStr which you need to read from your file.
NSError *jsonError = nil;
id allValues = [NSJSONSerialization JSONObjectWithData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]
options:0
error:&jsonError];
if(jsonError!=nil)
NSLog(#"Json_Err: %#",jsonError);
NSArray *array=allValues;
for (int ndx = 0; ndx < [array count]; ndx++) {
NSDictionary *stream = (NSDictionary *)[array objectAtIndex:ndx];
NSLog(#"%#",[stream objectForKey:#"kind"]);
NSArray *child = [[stream objectForKey:#"data"] objectForKey:#"children"];
//i am stuck here
for(int i =0; i <[child count];i++)
{
NSDictionary *childData = (NSDictionary *)[child objectAtIndex:i];
//NSLog(#"%#",[childData objectForKey:#"data"]);
NSLog(#"%#",[[childData objectForKey:#"data"] objectForKey:#"body"]);
}
}