How to get a NSDictionary with NSArray with file paths? - ios

I have a NSArray which looks like this:
#[#"file1", #"directory/testfile", #"directory/otherdir/testfile", #"otherdir/", #"otherdir/otherfile"]
And I'm trying to convert it to a NSDictionary which looks like this:
#{
#"directory/":#{
#"otherdir/":#{
#"testfile":[..some array with data..]}
},
#"testfile":[..some array with data..]
},
#"otherdir/":#{
#"otherfile":[..some array with data..]
},
#"file1":[..some array with data..]
}
Basically, a NSDictionary which looks like a file tree. Thanks in advance!
EDIT: The actual array I have is this:
(
"blog/",
"blog/code.css",
"blog/style.css",
"etc/",
"etc/awsservices.png",
"etc/speeds.png",
"etc/test/",
"etc/test/other/",
"etc/test/other/speeds.png",
"site/",
"site/dino.png",
"site/error.css",
"site/main.css",
"site/signet.min.js"
)
And the code I wrote for this:
-(NSDictionary*)buildDictionaryWithContentsOfPath:(NSMutableArray*)files {
NSString *subDir;
NSMutableDictionary *returnable = [[NSMutableDictionary alloc] initWithDictionary:#{}];
BOOL directory;
NSLog(#"%#", files);
for (S3ObjectSummary *objectSummary in files) {
if ([[objectSummary key] hasSuffix:#"/"]) {
if (subDir && [[objectSummary key] hasPrefix:subDir]) {
NSLog(#"prefixed %#", [objectSummary key]);
NSMutableDictionary *treeDict = [[NSMutableDictionary alloc] initWithDictionary:#{}];
[returnable[subDir] setObject:treeDict forKey:[objectSummary key]];
} else {
subDir = [objectSummary key];
NSLog(#"dir %#", [objectSummary key]);
NSMutableDictionary *treeDict = [[NSMutableDictionary alloc] initWithDictionary:#{}];
[returnable setObject:treeDict forKey:[objectSummary key]];
}
directory = true;
} else {
S3GetObjectMetadataRequest *getMetadataRequest = [[S3GetObjectMetadataRequest alloc] initWithKey:[objectSummary key] withBucket:self.bucket.name];
S3GetObjectMetadataResponse *getMetadataResponse = [self.client getObjectMetadata:getMetadataRequest];
if (![[objectSummary key] hasPrefix:subDir]) {
NSLog(#"file %#",[objectSummary key]);
[returnable setObject:#{#"filename":[objectSummary key], #"directory":#(directory), #"created_at":getMetadataResponse.lastModified} forKey:[objectSummary key]];
} else {
for (NSString __strong *pathComp in [[objectSummary key] pathComponents]) {
pathComp = [NSString stringWithFormat:#"%#/", pathComp];
NSLog(#"path component %#", pathComp);
if (![[objectSummary key] hasSuffix:#"/"]) {
if (returnable[pathComp]) {
NSLog(#"has comp %#", pathComp);
[returnable[pathComp] setObject:#{#"filename":[objectSummary key], #"directory":#(directory), #"created_at":getMetadataResponse.lastModified} forKey:[objectSummary key]];
}
}
}
}
directory = false;
}
//[self.fileTree addObject:#{#"filename":[objectSummary key], #"directory":#(directory), #"created_at":getMetadataResponse.lastModified}];
}
return returnable;
}
And the dictionary it returns:
{
"blog/" = {
"blog/code.css" = {
"created_at" = "2013-12-07 12:13:37 +0000";
directory = 0;
filename = "blog/code.css";
};
"blog/style.css" = {
"created_at" = "2013-12-07 12:13:36 +0000";
directory = 0;
filename = "blog/style.css";
};
};
"etc/" = {
"etc/awsservices.png" = {
"created_at" = "2013-12-07 12:26:37 +0000";
directory = 0;
filename = "etc/awsservices.png";
};
"etc/speeds.png" = {
"created_at" = "2013-12-07 13:29:27 +0000";
directory = 0;
filename = "etc/speeds.png";
};
// PROBLEM HERE
"etc/test/" = {
};
"etc/test/other/" = {
};
"etc/test/other/speeds.png" = {
"created_at" = "2013-12-07 17:29:21 +0000";
directory = 0;
filename = "etc/test/other/speeds.png";
};
// PROBLEM HERE
};
"site/" = {
"site/dino.png" = {
"created_at" = "2013-12-07 12:13:59 +0000";
directory = 0;
filename = "pmerino/dino.png";
};
"site/error.css" = {
"created_at" = "2013-12-07 12:13:59 +0000";
directory = 0;
filename = "pmerino/error.css";
};
"site/main.css" = {
"created_at" = "2013-12-07 12:13:59 +0000";
directory = 0;
filename = "pmerino/main.css";
};
"site/signet.min.js" = {
"created_at" = "2013-12-07 12:13:59 +0000";
directory = 0;
filename = "pmerino/signet.min.js";
};
};
}
As you can see, this part:
"etc/test/" = {
};
"etc/test/other/" = {
};
"etc/test/other/speeds.png" = {
"created_at" = "2013-12-07 17:29:21 +0000";
directory = 0;
filename = "etc/test/other/speeds.png";
};
Should look like this:
"etc/" = {
"test/" = {
"other/" = {
"speeds.png" = {
"created_at" = "2013-12-07 17:29:21 +0000";
directory = 0;
filename = "etc/test/other/speeds.png";
};
};
};
};

If I understand your problem correctly, this method should be helpful:
// Add the path to the tree. Returns the "node" for this path.
-(NSMutableDictionary *)addFile:(NSString *)path toTree:(NSMutableDictionary *)tree
{
NSMutableDictionary *node = tree;
// Split path into components:
NSArray *components = [path componentsSeparatedByString:#"/"];
// Create all intermediate dictionaries:
for (NSUInteger i = 0; i < [components count] - 1; i++) {
NSString *key = [components[i] stringByAppendingString:#"/"];
if (node[key] == nil) {
node[key] = [NSMutableDictionary dictionary];
}
node = node[key];
}
// Process last component, which is the file name,
// or "" in the case of a dictionary:
NSString *name = [components lastObject];
if ([name length] > 0) {
node[name] = [NSMutableDictionary dictionary];
node = node[name];
}
return node;
}
If you use it like this:
NSArray *files = ...; // Your array of files
NSMutableDictionary *tree = [NSMutableDictionary dictionary];
for (NSString *path in files) {
NSMutableDictionary *node = [self addFile:path toTree:tree];
BOOL isDir = [path hasSuffix:#"/"];
if (!isDir) {
node[#"filename"] = path;
}
}
the resulting dictionary is
{
"blog/" = {
"code.css" = {
filename = "blog/code.css";
};
"style.css" = {
filename = "blog/style.css";
};
};
"etc/" = {
"awsservices.png" = {
filename = "etc/awsservices.png";
};
"speeds.png" = {
filename = "etc/speeds.png";
};
"test/" = {
"other/" = {
"speeds.png" = {
filename = "etc/test/other/speeds.png";
};
};
};
};
"site/" = {
"dino.png" = {
filename = "site/dino.png";
};
"error.css" = {
filename = "site/error.css";
};
"main.css" = {
filename = "site/main.css";
};
"signet.min.js" = {
filename = "site/signet.min.js";
};
};
}

Related

Check and replace all null values with empty string in NSDictionary/NSArray

I am storing my json response in a NSDictionary and this dictionary contains various array, so I want to replace all the null values with #"" empty string.
{
Specialities = (
{
ApprovalStatus = Unapproved;
CurrencyCode = "<null>";
Packages = (
{
AssetId = 157965;
BasePrice = 10000;
BookingAdvance = 100;
Currency = INR;
Details = "<null>";
DiscountedPrice = 9000;
Id = 16579;
IsBestOffer = 1;
IsPopular = 1;
LineItems = (
{
IconClass = "fa-check";
Text = "A DVD with all edited and unedited images";
}
);
PackageVersion = 123955;
PriceUnit = 3;
Quantity = 4;
SpecialityId = 22;
Status = Rejected;
Tags = (
53
);
TermsAndConditions = "<null>";
Title = Test;
}
);
Photos = (
157965,
157964
);
ServiceDescription = 43534;
Speciality = 22;
SpecialityName = "Wedding Photographer";
UserFRPs = (
{
AssetId = 157965;
CurrencyCode = INR;
DiscountedPrice = 800;
FRPId = 13;
Id = 4559;
Price = 1000;
SpecialityId = 22;
Status = Active;
},
{
AssetId = 565441;
CurrencyCode = INR;
DiscountedPrice = 9000;
FRPId = 18;
Id = 5559;
Price = 10000;
SpecialityId = 22;
Status = Active;
}
);
Videos = (
{
VideoId = DaWOguXZbNA;
VideoLink = "http://www.youtube.com/watch?v=DaWOguXZbNA";
VideoType = YouTube;
},
{
VideoId = DGVJtAHzzDQ;
VideoLink = "http://www.youtube.com/watch?v=DGVJtAHzzDQ";
VideoType = YouTube;
},
{
VideoId = "_zxKLZR-xuk";
VideoLink = "http://www.youtube.com/watch?v=_zxKLZR-xuk";
VideoType = YouTube;
},
{
VideoId = 5SkBZcvuuQs;
VideoLink = "http://www.youtube.com/watch?v=5SkBZcvuuQs";
VideoType = YouTube;
},
{
VideoId = "H_Xi-lVB4Zw";
VideoLink = "http://www.youtube.com/watch?v=H_Xi-lVB4Zw";
VideoType = YouTube;
},
{
VideoId = TWhSjpsGvPQ;
VideoLink = "http://www.youtube.com/watch?v=TWhSjpsGvPQ";
VideoType = YouTube;
},
{
VideoId = N2CJrhHEydA;
VideoLink = "http://www.youtube.com/watch?v=N2CJrhHEydA";
VideoType = YouTube;
},
{
VideoId = Lq6faQVYcwY;
VideoLink = "http://www.youtube.com/watch?v=Lq6faQVYcwY";
VideoType = YouTube;
},
{
VideoId = v8WjMiodcKo;
VideoLink = "http://www.youtube.com/watch?v=v8WjMiodcKo";
VideoType = YouTube;
}
);
},
{
ApprovalStatus = Unapproved;
CurrencyCode = "<null>";
Packages = "<null>";
Photos = (
157967
);
ServiceDescription = Ddhd;
Speciality = 37;
SpecialityName = "Hair and Makeup Stylist";
UserFRPs = (
{
AssetId = 157967;
CurrencyCode = INR;
DiscountedPrice = 900;
FRPId = 34;
Id = 4560;
Price = 1000;
SpecialityId = 37;
Status = Active;
}
);
Videos = (
{
VideoId = "onvkllwM-OI";
VideoLink = "http://www.youtube.com/watch?v=onvkllwM-OI";
VideoType = YouTube;
},
{
VideoId = "_-cRVdTW2s8";
VideoLink = "http://www.youtube.com/watch?v=_-cRVdTW2s8";
VideoType = YouTube;
},
{
VideoId = DGVJtAHzzDQ;
VideoLink = "http://www.youtube.com/watch?v=DGVJtAHzzDQ";
VideoType = YouTube;
}
);
},
{
ApprovalStatus = Unapproved;
CurrencyCode = "<null>";
Packages = "<null>";
Photos = (
157963,
157962,
157961
);
ServiceDescription = Test;
Speciality = 55;
SpecialityName = Transport;
UserFRPs = "<null>";
Videos = (
{
VideoId = "cRchvv_dB2c";
VideoLink = "http://www.youtube.com/watch?v=cRchvv_dB2c";
VideoType = YouTube;
},
{
VideoId = "onvkllwM-OI";
VideoLink = "http://www.youtube.com/watch?v=onvkllwM-OI";
VideoType = YouTube;
},
{
VideoId = DGVJtAHzzDQ;
VideoLink = "http://www.youtube.com/watch?v=DGVJtAHzzDQ";
VideoType = YouTube;
}
);
},
{
ApprovalStatus = Unapproved;
CurrencyCode = "<null>";
Packages = "<null>";
Photos = "<null>";
ServiceDescription = Baby;
Speciality = 5;
SpecialityName = "Children/Babies Photographer";
UserFRPs = "<null>";
Videos = (
{
VideoId = "cRchvv_dB2c";
VideoLink = "http://www.youtube.com/watch?v=cRchvv_dB2c";
VideoType = YouTube;
},
{
VideoId = DGVJtAHzzDQ;
VideoLink = "http://www.youtube.com/watch?v=DGVJtAHzzDQ";
VideoType = YouTube;
}
);
},
}
I want all null values to be replace by empty string.
Then just do that
NSString *json = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:yourDictionary options:0 error:nil] encoding: NSUTF8StringEncoding];
NSString *jsonWithoutNulls = [json stringByReplacingOccurrencesOfString:#"<null>" withString:#""];
NSData *data = [jsonWithoutNulls dataUsingEncoding:NSUTF8StringEncoding]
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
I prefer to use Macros to determine null values.
#define IS_NULL(value) (value != nil && value != Nil && value != NULL && value != (id)[NSNull null])
and I invoke it like
if (IS_NULL(CurrencyCode))
{
//insert ""
}else
{
//do necessary updates
}
OR you can also use the following method ,
-(BOOL) isNull: (NSString*)value{
if ([value isEqualToString:#"<null>"]){
return false;
}
return true;
}
and you can invoke it like,
if (isNull(currencyType))
{
//insert #""
}else{
//do necessary updates
}
Try this this is mine code i am using i hope it would be helpful!!
func checkDictionary(let dict:NSMutableDictionary)
{
let keys = Array(dict.allKeys)
for i in keys
{
let checkvalue = dict.valueForKey(i as! String)
if checkvalue! .isKindOfClass(NSNull)
{
dict.setObject("", forKey: i as! NSString)
}
else if checkvalue!.isKindOfClass(NSDictionary)
{
let dic = checkvalue as! NSDictionary
let dicts = dic.mutableCopy()
self.checkDictionary(dicts as! NSMutableDictionary)
dict.setObject(dicts, forKey: i as! NSString)
}
else if checkvalue! .isKindOfClass(NSArray)
{
let keys2 = checkvalue as! NSArray
let keys1 = keys2.mutableCopy() as! NSMutableArray
dict.setObject(keys1, forKey: i as! NSString)
for j in keys1
{
if j .isKindOfClass(NSNull)
{
keys1.replaceObjectAtIndex(keys1.indexOfObject(j), withObject:"")
}
if j.isKindOfClass(NSDictionary)
{
let dic = j as! NSDictionary
let dicts = dic.mutableCopy()
keys1.replaceObjectAtIndex(keys1.indexOfObject(j), withObject: dicts)
self .checkDictionary(dicts as! NSMutableDictionary)
}
}
}
}
}
In objective-C Try this!!
-(void)CheckDictionary:(NSMutableDictionary *)dic
{
NSArray *Arr = [dic allKeys];
for (int i = 0; i<Arr.count; i++)
{
if ([[dic valueForKey:[Arr objectAtIndex:i]] isKindOfClass:[NSNull class]])
{
[dic setObject:#"" forKey:[Arr objectAtIndex:i]];
}
else if ([[dic valueForKey:[Arr objectAtIndex:i]] isKindOfClass:[NSDictionary class]])
{
NSMutableDictionary *dict = [[dic valueForKey:[Arr objectAtIndex:i]] mutableCopy];
[dic setObject:dict forKey:[Arr objectAtIndex:i]];
[self CheckDictionary:dict];
}
else if ([[dic valueForKey:[Arr objectAtIndex:i]] isKindOfClass:[NSMutableArray class]])
{
NSMutableArray *Arr12 = [dic valueForKey:[Arr objectAtIndex:i]];
for (int j = 0; j<Arr12.count; j++)
{
if ([[Arr12 objectAtIndex:j] isKindOfClass:[NSDictionary class]])
{
NSDictionary *dict123 = [Arr12 objectAtIndex:j];
NSMutableDictionary *dict = [dict123 mutableCopy];
[Arr12 replaceObjectAtIndex:j withObject:dict];
[self CheckDictionary:dict];
}
}
}
}
}
And Just pass the whole dictionary when you call this method I hope it would be helpful!!
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:responseObject options: NSJSONReadingMutableContainers error: nil];
if (dictionary)
{
NSMutableDictionary *dict = [dictionary mutableCopy];
[self CheckDictionary:dict];
dictionary = [NSDictionary dictionaryWithDictionary:dict];
}
This is how we do it
#interface NSMutableArray (JSON)
- (void)recursivelyRemoveNulls;
#end
#implementation NSMutableArray (JSON)
- (void)recursivelyRemoveNulls
{
[self enumerateObjectsUsingBlock:^(id value, NSUInteger __unused idx, BOOL __unused *nestedStop)
{
if ([value isKindOfClass:[NSDictionary class]])
{
NSMutableDictionary *modifiedValue = [NSMutableDictionary dictionaryWithDictionary:value];
[modifiedValue recursivelyRemoveNulls];
[self removeObject:value];
[self addObject:modifiedValue];
}
else if ([value isKindOfClass:[NSArray class]])
{
NSMutableArray *modifiedValue = [NSMutableArray arrayWithArray:value];
[modifiedValue recursivelyRemoveNulls];
[self removeObject:value];
[self addObject:modifiedValue];
}
}];
}
#end
#interface NSMutableDictionary (JSON)
- (void)recursivelyRemoveNulls;
#end
#implementation NSMutableDictionary (JSON)
- (void)recursivelyRemoveNulls
{
[self enumerateKeysAndObjectsUsingBlock:^(NSString *key, id value, BOOL __unused *stop)
{
if (value == [NSNull null] || value == nil)
{
[self removeObjectForKey:key];
}
else if ([value isKindOfClass:[NSDictionary class]])
{
NSMutableDictionary *modifiedValue = [NSMutableDictionary dictionaryWithDictionary:value];
[modifiedValue recursivelyRemoveNulls];
self[key] = modifiedValue;
}
else if ([value isKindOfClass:[NSArray class]])
{
NSMutableArray *modifiedValue = [NSMutableArray arrayWithArray:value];
[modifiedValue recursivelyRemoveNulls];
self[key] = modifiedValue;
}
}];
}
#end
The short code you can use here:-
NSString * newValue=[self isNotNull:[your Object here]] ? [your Object here] : #"Value that you want to replace";
- (BOOL)isNull:(NSObject *)object {
if (!object) return YES;
else if (object == [NSNull null]) return YES;
else if ([object isKindOfClass:[NSString class]]) {
return ([((NSString *)object)isEqualToString : #""]
|| [((NSString *)object)isEqualToString : #"null"]
|| [((NSString *)object)isEqualToString : #"<null>"]
|| [((NSString *)object)isEqualToString : #"(null)"]
);
}
return NO;
}
- (BOOL)isNotNull:(NSObject *)object {
return ![self isNull:object];
}

How to fetch elements from NSArray in Objective C

I'm using a bus timetable API and want to display the nearby bus stop according to user current location. I've already got the the JSON response through url and parsed JSON to NSArray. The NSArray looks like this.
{
result = {
distance = "0.00003292029";
lat = "-37.92091";
"location_name" = "Monash Medical Centre/Clayton Rd ";
lon = "145.120682";
"route_type" = 2;
"stop_id" = 16518;
suburb = Clayton;
"transport_type" = bus;
};
type = stop;
},
{
result = {
distance = "0.00003728643";
lat = "-37.92227";
"location_name" = "Monash Surgical Private Hospital/291 Clayton Rd ";
lon = "145.1202";
"route_type" = 2;
"stop_id" = 24348;
suburb = Clayton;
"transport_type" = bus;
};
type = stop;
},
{
result = {
distance = "0.00003804303";
lat = "-37.9230766";
"location_name" = "Clayton Railway Station/Clayton Rd ";
lon = "145.120209";
"route_type" = 2;
"stop_id" = 22809;
suburb = Clayton;
"transport_type" = bus;
};
type = stop;
},
{
result = {
distance = "0.00003976311";
lat = "-37.9186172";
"location_name" = "Monash Specialist Centre/Clayton Rd ";
lon = "145.121033";
"route_type" = 2;
"stop_id" = 22807;
suburb = Clayton;
"transport_type" = bus;
};
type = stop;
},
{
result = {
distance = "0.00004085229";
lat = "-37.9186478";
"location_name" = "Dixon St/Clayton Rd ";
lon = "145.120911";
"route_type" = 2;
"stop_id" = 13889;
suburb = Clayton;
"transport_type" = bus;
};
type = stop;
}
)
My question is how to get the latitude and longitude from this NSArray. I wrote these code but it returns nil.
NSMutableArray *coordinateLatit = [[NSMutableArray alloc]init];
for (int i = 0; i<nearbyStop.count; i++) {
NSString *latit = [[nearbyStop objectAtIndex:1] objectForKey:#"lat"];
if(latit == nil)
{
NSLog(#"there is no data");
}
else
{
[coordinateLatit addObject:latit];
}
}
And also i want to display the stops(use longitude&latitude from NSArray) on MKMapView, how should i manage to implement the MKLocalSearchRequest
Appreciate it if anyone can help me!
Your code overlooked the extra nested result level.
NSMutableArray *coordinateLatit=[[NSMutableArray alloc]init];
for(NSDictionary *d in nearbyStop)
{
NSString *latit=d[#"result"][#"lat"];
if(lat) [coordinateLatit addObject:latit];
}
-(id) doApiCall:(NSString*)apiCall useCache:(BOOL)useCache
{
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#", mBaseURL, [MapViewController signApiCall:apiCall]]];
id response = [self httpWrapper:url];
NSLog( #"%#", response );
return response;
}
-(id) httpWrapper:(NSURL*)url
{
__block id response = nil;
void (^doStuff)() = ^void()
{
int retry = 3;
NSError * error;
while( retry > 0) {
NSData * data = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:600] returningResponse:nil error:&error ];
if( data != nil )
{
response = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if( response != nil)
retry = 0;
}
if(data == nil || response == nil)
{
NSLog(#"Bad response %#", url);
NSLog(#"%#", error);
--retry;
}
}
};
doStuff();
return response;
}
-(NSArray*) nearby:(CLLocation*)location
{
return [self doApiCall:[NSString stringWithFormat:#"/v2/nearme/latitude/%f/longitude/%f?limit=5", location.coordinate.latitude, location.coordinate.longitude]];
}
Here is the code i'm using to call the API. I use id for the response from url request. so does nearby method returns NSArray type?
you miss a level of the json response, it should be
for (Stop *stop in nearbyStop) {
NSString *latit = [[stop objectForKey:#"result"] objectForKey:#"lat"];
if(latit == nil)
{
NSLog(#"there is no data");
}
else
{
[coordinateLatit addObject:latit];
}
}

IOS: how to join 2 Dictionaries into 1 dictionary??

in my project i applied the following code
NSDictionary *dict6 = [self cleanJsonToObject:responseData];
NSLog(#"str : %#",dict6);
diagnosisdict = [[[dict6 objectForKey:#"diagnoses"] objectAtIndex:0] objectForKey:#"DiagnosesHospitals"];
diagnosedictforname = [[[dict6 objectForKey:#"diagnoses"]objectAtIndex:0]objectForKey:#"Diagnoses"];
NSLog(#" for ref id =%# ,name of diagnose=%# data is= %#",refidstr,diagnosedictforname ,diagnosisdict);
and the output in console is comes out as in the form
str : {
diagnoses = (
{
Diagnoses = {
"diagnosis_name" = "TRANSIENT ISCHEMIA";
};
DiagnosesHospitals = {
"charge_amt" = "1300.00";
discharges = "11200.00";
"hospital_id" = 3341;
id = 163080;
"medicare_amt" = "100.00";
"total_amt" = "1100.00";
};
}
);
response = 200;
}
ref id =3341 ,name of diagnose={
"diagnosis_name" = "TRANSIENT ISCHEMIA";
} data is= {
"charge_amt" = "1300.00";
discharges = "11200.00";
"hospital_id" = 3341;
id = 163080;
"medicare_amt" = "100.00";
"total_amt" = "1100.00";
}
now i just want to embed the values of both the Dictionaries into one dictionary
someone please help me to sort out this issue.
Make a mutable copy of the first dictionary:
NSMutableDictionary * mutDic = [dic1 mutableCopy];
and then:
[mutDic addEntriesFromDictionary:dic2];
Try this code:
NSDictionary *dict6 = [self cleanJsonToObject:responseData];
NSLog(#"str : %#",dict6);
NSMutableDictionary *diagnosisdict = [[[dict6 objectForKey:#"diagnoses"] objectAtIndex:0] objectForKey:#"DiagnosesHospitals"];
NSDictionary *diagnosedictforname = [[[dict6 objectForKey:#"diagnoses"]objectAtIndex:0]objectForKey:#"Diagnoses"];
NSArray *keys = [diagnosedictforname allKeys];
for (int i =0; i < keys.count; i++) {
NSString *key = [keys objectAtIndex:i];
[diagnosisdict setValue:[diagnosedictforname valueForKey:key] forKey:key];
}
NSLog(#"your dic -> %#", diagnosisdict);

Find sub key in NSDictionary

I have a large NSDictionary. Fx.
"m:GetFolderResponse" = {
"m:ResponseMessages" = {
"m:GetFolderResponseMessage" = {
ResponseClass = Success;
"m:Folders" = {
"t:CalendarFolder" = {
"t:ChildFolderCount" = {
text = 0;
};
"t:DisplayName" = {
text = Calendar;
};
"t:FolderId" = {
ChangeKey = "AgAAABYAAABGewbOYWpKSrW/k23iIoFkAPJWd7/8";
Id = "AAMkADkwOWE2NjEyLTMwZWQtNGYyMy05OGQ1LWZjZjFkZGY5MTBhMAAuAAAAAAC1cjo8jkv5SKjQt5WaSmd1AQBGewbOYWpKSrW/k23iIoFkAPJWc0NrAAA=";
};
};
};
"m:ResponseCode" = {
text = NoError;
};
};
};
"xmlns:m" = "http://schemas.microsoft.com/exchange/services/2006/messages";
"xmlns:t" = "http://schemas.microsoft.com/exchange/services/2006/types";
};
}
As you might have guessed, there can be multiple in the m:Folders. Therefore I would like to find m:Folders child, where t:DisplayName is equal to a variable value. How can I do this?
- (void)filterMutableDictionary:(NSDictionary*)aDictionary andKeyName:(NSString *)keyName
{
if ([keyName isEqualToString:#"t:CalendarFolder"]) {
if ([[[aDictionary objectForKey:#"t:DisplayName"] objectForKey:#"text"] isEqualToString:searchCalendarName]) {
NSDictionary *temp = [aDictionary objectForKey:#"t:FolderId"];
CalID = [temp objectForKey:#"Id"];
CalChangeID = [temp objectForKey:#"ChangeKey"];
}
}
// enumerate key/values, filtering appropriately, recursing as necessary
NSLog(#"%#",aDictionary);
[aDictionary enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
if ([value isKindOfClass: [NSMutableDictionary class]] || [value isKindOfClass: [NSDictionary class]]) {
[self filterMutableDictionary: value andKeyName:key];
}
}];
}

how to find location of Id in NSMutableArray

I have NSMutableArray data as below.
(
{
Id = "-1";
NameEn = Country;
},
{
Id = 14;
NameEn = Iran;
},
{
Id = 11;
NameEn = Jordan;
},
{
Id = 5;
NameEn = "United Arab Emirates";
},
{
Id = 4;
NameEn = "Suadi Arabia";
},
{
Id = 3;
NameEn = Kuwait;
},
{
Id = 10;
NameEn = Yemen;
},
{
Id = 6;
NameEn = Oman;
},
{
Id = 12;
NameEn = Syria;
},
{
Id = 7;
NameEn = Qatar;
},
{
Id = 13;
NameEn = Lebanon;
},
{
Id = 1;
NameEn = Egypt;
},
{
Id = 8;
NameEn = "Bahrain Kingdom";
}
)
I want to find the location where Id=5.
Any idea how can I do?
I tried with below.
NSString *myCountry = [[NSUserDefaults standardUserDefaults] valueForKey:#"mCountryId"];
NSUInteger indexOfTheObject = [feedsCountry indexOfObject: myCountry];
NSLog(#"indexOfTheObject===%i==%#", indexOfTheObject, myCountry);
if (NSNotFound == indexOfTheObject) {
NSLog(#"not found...");
}
But I get output as not found... for mCountryId as 5.
Use an NSDictionary instead, and key your entries by Id; e.g.:
NSMutableDictionary* dictionary = [NSMutableDictionary new];
[dictionary setObject:#"Egypt" forKey:#"1"];
// (etc...)
EDIT: If you already have an array and can not change that, use a for loop like this:
for(NSDictionary* entry in givenArray){
NSString* key = [entry objectForKey:#"Id"];
NSString* value = [entry objectForKey:#"NameEn"];
[dictionary setObject:value forKey:key];
}
NSPredicate * filter = [NSPredicate predicateWithFormat:#"Id = 5"];
NSArray * filtered = [array filteredArrayUsingPredicate:filter];
The first object in filtered is the dictionary with Id = 5

Resources