I have the json data were within the first array I main category array with name "Response" within that I have parent category array with name "0" within which I have child category array with name "0" and here is my json format
{"Response":[{"menuname":"Jewellery","menuid":"1","0":[{"catname":"Rings","catid":"1","0":[{"scatname":"Engagement Rings","scatid":"4"},{"scatname":"Wedding Rings","scatid":"5"},{"scatname":"kk","scatid":"35"}]},{"catname":"Pendants","catid":"2","0":[{"scatname":"Office Wear","scatid":"8"}]},{"catname":"Bracelets","catid":"3","0":[{"scatname":"Studded","scatid":"9"}]},{"catname":"Earrings","catid":"6","0":[{"scatname":"Ethnic Jhumkas","scatid":"7"}]},{"catname":"Chain's","catid":"33","0":[]},{"catname":"Jewel","catid":"34","0":[]}]},{"menuname":"Collections","menuid":"2","0":[{"catname":"SOUND OF LOVE","catid":"15","0":[{"scatname":"LOVE BRACELET","scatid":"16"}]},{"catname":"COLORFUL AFFAIR","catid":"17","0":[{"scatname":"Passion ring","scatid":"18"}]},{"catname":"Evermore Collection","catid":"19","0":[]},{"catname":"BOARDROOM GLAM ","catid":"20","0":[]},{"catname":"ETERNAL GOLD","catid":"21","0":[]},{"catname":"FASHIONISTA COLLECTION","catid":"22","0":[]}]},{"menuname":"Gold Coin","menuid":"3","0":[{"catname":"SOUND OF LOVE","catid":"15","0":[{"scatname":"LOVE BRACELET","scatid":"16"}]},{"catname":"COLORFUL AFFAIR","catid":"17","0":[{"scatname":"Passion ring","scatid":"18"}]},{"catname":"Evermore Collection","catid":"19","0":[]},{"catname":"BOARDROOM GLAM ","catid":"20","0":[]},{"catname":"ETERNAL GOLD","catid":"21","0":[]},{"catname":"FASHIONISTA COLLECTION","catid":"22","0":[]}]},{"menuname":"OFF THE SHELF","menuid":"4","0":[{"catname":"testing from pixel","catid":"13","0":[]},{"catname":"New pixel","catid":"23","0":[]},{"catname":"Evermore Collection","catid":"19","0":[]},{"catname":"BOARDROOM GLAM ","catid":"20","0":[]},{"catname":"ETERNAL GOLD","catid":"21","0":[]},{"catname":"FASHIONISTA COLLECTION","catid":"22","0":[]}]}]}
and I want to display in expandable tableview as below
Jewellery
Rings
Engagement Rings
Wedding Rings
kk
Pendants
Ofice Wear
Collections
Sound Of Love
Love bracelet
Colorful Affair
Passion ring
Here is the code I used in viewdidLoad
NSDictionary *pJson;
NSMutableString *postStr = [NSMutableString stringWithString:kURL];
[postStr appendString:[NSString stringWithFormat:#"?tag=%#&id=%#",kCategoryFilter,kPrecious]];
[postStr setString:[postStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:postStr]];
NSLog(#"%#",postStr);
[request setHTTPMethod:#"POST"];
_connection = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES];
NSURL *url = [NSURL URLWithString:postStr];
NSData *data = [NSData dataWithContentsOfURL:url];
pJson = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSLog(#"%#",pJson);
NSMutableArray *arr = [pJson objectForKey:#"Response"];
NSLog(#"%lu",(unsigned long)arr.count);
NSMutableDictionary *dict2 =[[NSMutableDictionary alloc]init];// [arr objectAtIndex:NSIndexPath.row];
[dict2 setObject:arr forKey:#"dictionary1"];
dict2 = [arr objectAtIndex:0];
NSArray *arr1 =[dict2 objectForKey:#"0"];
NSLog(#"%lu",(unsigned long)arr1.count);
NSUInteger y;
for (int i=0;i<arr.count;i++) {
NSString *ring_data = [[arr objectAtIndex:i]objectForKey:#"menuname"];
NSString *id_data = [[arr objectAtIndex:i]objectForKey:#"menuid"];
NSLog(#"AUTHOR: %#",ring_data);
NSLog(#"%#",id_data);
dictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:
ring_data,#"menuname",id_data,#"menuId",nil];
[myObject addObject:dictionary];
NSMutableArray *arr1 = [dict2 objectForKey:#"0"];
NSLog(#"%lu",(unsigned long)arr1.count);
y = arr.count;
for (NSUInteger i=0;i<arr1.count;i++) {
NSArray *count = [[[arr1 objectAtIndex:i] objectForKey:arr]valueForKey:#"catname"];
NSString *myCount = [NSString stringWithFormat:#"%lu",(unsigned long)[count count]];
NSString *ring_data = [[arr1 objectAtIndex:i]objectForKey:#"catname"];
NSLog(#"AUTHOR: %#",ring_data);
// NSLog(#"%#",catname_data);
dictionary1 = [NSMutableDictionary dictionaryWithObjectsAndKeys:
ring_data,#"catname",
nil];
[myObject1 addObject:dictionary1];
}
}
I tried some coding for you.Follow that code and customize where you want to add to array and where to set dictionary.
NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];
NSArray *array=[jsonArray objectForKey:#"Response"];
for (int i=0;i<[array count];i++)
{
NSMutableDictionary *dict = [array objectAtIndex:i];
NSMutableArray *arrayDictValue = [dict valueForKey:[NSString stringWithFormat:#"%d",0]];
NSString *strMenuName = [NSString stringWithFormat:#"%#",[arrayDictValue valueForKey:#"menuname"]];
NSString *strMenuID = [NSString stringWithFormat:#"%#",[arrayDictValue valueForKey:#"menuid"]];
NSLog(#"The strMenuName is-%#",strMenuName);
NSLog(#"The strMenuID is-%#",strMenuID);
for (int j=0; j<[arrayDictValue count]; i++)
{
NSMutableDictionary *dictInside = [arrayDictValue objectAtIndex:j];
NSArray *arrayInsideDict = [dictInside valueForKey:#"0"];
for (int k =0; k<[arrayInsideDict count]; i++)
{
NSString *strCatName = [NSString stringWithFormat:#"%#",[[arrayInsideDict objectAtIndex:k ]valueForKey:#"catname"]];
NSString *strCatID = [NSString stringWithFormat:#"%#",[[arrayInsideDict objectAtIndex:k ]valueForKey:#"catid"]];
NSLog(#"The strCateName is-%#",strCatName);
NSLog(#"The strCatID is-%#",strCatID);
NSMutableDictionary *dictInArray = [[arrayInsideDict objectAtIndex:0] valueForKey:#"0"];
NSString *strSCatName = [NSString stringWithFormat:#"%#",[dictInArray valueForKey:#"scatname"]];
NSString *strSCatID = [NSString stringWithFormat:#"%#",[dictInArray valueForKey:#"scatid"]];
NSLog(#"the strSCatName is - %#",strSCatName);
NSLog(#"the strSCatID is - %#",strSCatID);
}
}
}
I have an NSArray with NSDictionary inside. It looks like:
etc.
I need to sort it by date inside NSDictionary. I need something like this:
How can I do this? Here is my method which gives me first unsorted array:
- (void)iterateOverDocumentsDirectory
{
arrayWithFiles = [NSMutableArray new];
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirPath = [paths objectAtIndex:0];
NSString *finalPathToFolder = [NSString stringWithFormat:#"%#/", documentsDirPath];
albumNames = [[fileManager contentsOfDirectoryAtPath:finalPathToFolder error:&error] mutableCopy];
if (albumNames == nil) {
// error...
}
for (NSString *album in albumNames)
{
NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] init];
[tempDict setValue:album forKey:#"name"];
NSString *finalPathToFiles = [NSString stringWithFormat:#"%#/%#", documentsDirPath, album];
NSArray *tempArray = [fileManager contentsOfDirectoryAtPath:finalPathToFiles error:&error];
NSMutableArray *arrayWithEachFiles = [NSMutableArray new];
for (NSString *tempString in tempArray)
{
NSMutableDictionary *eachFileDict = [[NSMutableDictionary alloc] init];
NSString *pathToFile = [NSString stringWithFormat:#"%#/%#/%#", documentsDirPath, album, tempString];
[eachFileDict setValue:pathToFile forKey:#"path"];
NSDictionary *filePathsArray1 = [[NSFileManager defaultManager] attributesOfItemAtPath:pathToFile error:nil];
NSDate *modifiedDate = [filePathsArray1 objectForKey:NSFileCreationDate];
[eachFileDict setValue:modifiedDate forKey:#"date"];
[arrayWithEachFiles addObject:eachFileDict];
}
NSSortDescriptor *ageDescriptor = [[NSSortDescriptor alloc] initWithKey:#"date" ascending:YES];
NSArray *sortDescriptors = #[ageDescriptor];
NSArray *sortedArrayWithFiles = [[arrayWithEachFiles sortedArrayUsingDescriptors:sortDescriptors] mutableCopy];
[tempDict setValue:sortedArrayWithFiles forKey:#"files"];
[arrayWithFiles addObject:tempDict];
}
}
Use following code for sorting the array of dictionaries:
NSArray * sortedArray = [myArray sortedArrayUsingComparator:^(id obj1, id obj2) {
NSNumber *rating1 = [(NSDictionary *)obj1 objectForKey:#"date"];
NSNumber *rating2 = [(NSDictionary *)obj2 objectForKey:#"date"];
return [rating1 compare:rating2];
}];
You can sort it easily by using sortArrayUsingComparator:
[array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
return //pseudo-code: {obj1->dict->date isLaterThan obj2->dict->date};
}];
I sort it. Not sure that my code is clear and well optimized. But here is a solution:
NSMutableArray *masterArray = [NSMutableArray new];
NSMutableArray *sameDates = [NSMutableArray new];
BOOL started = NO;
NSString *prevDate;
for (NSDictionary *dict in sortedArrayWithFiles)
{
NSString *tempString = [dict objectForKey:#"date"];
if (started)
{
if ([tempString isEqualToString:prevDate])
{
[sameDates addObject:dict];
}
else
{
NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] init];
[tempDict setValue:tempString forKey:tempString];
[tempDict setValue:sameDates forKey:#"files"];
[masterArray addObject:tempDict];
prevDate = tempString;
[sameDates removeAllObjects];
[sameDates addObject:tempString];
}
}
else
{
// first element
started = YES;
prevDate = tempString;
[sameDates addObject:dict];
}
}
// last value
NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] init];
[tempDict setValue:prevDate forKey:prevDate];
[tempDict setValue:sameDates forKey:#"files"];
[masterArray addObject:tempDict];
In master array we store array with dictionaries separated by date.
I am trying to search any files using search display controller. But file inside files are not displaying in tableview. That means subfolder/files are not retrieved.
For getting file and folder I am using this code. I don't understand why subfiles are not displaying.
if(metadata.isDirectory)
{
marrFiles = [[NSMutableArray alloc]init];
for (DBMetadata *dbObject in metadata.contents)
{
if (!dbObject.isDirectory)
{
NSString *fileName = [dbObject.path lastPathComponent];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
NSString *stringSize = [NSString stringWithFormat:#"%#",[dbObject humanReadableSize]];
NSDate *modificationDate = [dbObject lastModifiedDate];
NSString *dateString = [dateFormatter stringFromDate:modificationDate];
dateString = [dateString createdTimeString];
[dict setValue:fileName forKey:#"File"];
NSString *stringInfo = [NSString stringWithFormat:#"%# %#",stringSize,dateString];
[dict setValue:stringInfo forKey:#"Size"];
[dict setValue:#"No" forKey:#"isSelected"];
[marrFiles addObject:dict];
}
else
{
NSString *fileName = [dbObject.path lastPathComponent];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setValue:#"No" forKey:#"isSelected"];
[dict setValue:fileName forKey:[NSString stringWithFormat:#"File"]];
[marrFiles addObject:dict];
}
}
[tblDropbox reloadData];
}
else
{
NSMutableArray *listFile=[NSMutableArray array];
for (DBMetadata *file in metadata.contents) {
[listFile addObject:file.filename];
}
}
[MBProgressHUD hideHUDForView:self.view animated:YES];
I have an array that loaded with data from other method. The data type is like that in the debug for KEYS as in the code.
<__NSArrayI 0x9e82fc0>(
{
"choice_name" = "Data0";
},
{
"choice_name" = "Data1";
},
{
"choice_name" = "Data2";
},
Then I have called it twice in different method as I commented below and I get the value of the arrray: array0 or array1 nil. Where would be my problem?
- (void)requestPosistion:(ASIFormDataRequest *)request{
NSData *responseData = [request responseData];
NSString *jsonString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSDictionary *result = [jsonString JSONValue];
[jsonString release];
if (![SettingVO isValidResponce:result]) return;
CXMLDocument *doc = [[[CXMLDocument alloc] initWithXMLString:[result objectForKey:#"Response"] options:0 error:nil] autorelease];
NSArray *nodes = [doc nodesForXPath:#"/root" error:nil];
NSLog(#"choiceList is %#", nodes);
if([[[[nodes objectAtIndex:0] attributeForName:#"success"] stringValue] isEqualToString:#"true"])
{
NSArray *nodes3 = NULL;
nodes3 = [doc nodesForXPath:#"/root/cl_choicelist/cl_choice" error:nil];
NSLog(#"node3%#", nodes3);
res = [[NSMutableArray alloc] init];
for (CXMLElement *node in nodes3) {
item = [[NSMutableDictionary alloc] init];
int counter;
for(counter = 0; counter < [node childCount]; counter++) {
[item setObject:[[node childAtIndex:counter] stringValue] forKey:[[node childAtIndex:counter] name]];
}
[item setObject:[[node attributeForName:#"choice_name"] stringValue] forKey:#"choice_name"];
NSLog(#"item %#", item);
[res addObject:item];
[item release];
}
NSLog(#"res %#", res);
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *plistDict = [[NSDictionary alloc] initWithObjects:res forKeys:res];
//NSArray *keys = [plistDict allKeys];
//NSArray *array0 = [[NSArray alloc] initWithArray:[plistDict valueForKey:#"choice_name"]]; //array0 = nil.
NSArray *array1 = [plistDict objectForKey:#"choice_name"]; //array1 = nil.
Working code looks like that:
[[res objectAtIndex:0] objectForKey:#"choice_name"] //returns Data0
[[res objectAtIndex:1] objectForKey:#"choice_name"] //returns Data1
Most probably you want to use "indexPath" at objectAtIndex:
[[res objectAtIndex:[indexPath row]] objectForKey:#"choice_name"]
<__NSArrayI 0x9e82fc0>( { "choice_name" = "Data0"; }, { "choice_name" = "Data1"; }, { "choice_name" = "Data2"; },
This is an array. Inside the array you have object of NSDictionary with key "choice_name".
So in order to retrieve you need to iterate through the array to get all the kvp.
Replace your line with:
NSString *str = [plistDict valueForKey:#"choice_name"];
You have string for that key nor array.
Is always good to make sure your plistDict is not nil.
In NSDictionary you can have onelly one pair with key #choice_name. Even if you "put" more then one in NSDictionary, all other will just override previous value.
so valueForKey can return onelly one object and not the whole array, because there is onelly one key #choice_name.
I am trying to save an NSMutable Array and NSString into plist and then if it exists initialize the value from plist. However when I re run the app, the values do not get initialize as it is suppose to. So far the following is what I have.
if (self = [super init]) {
NSString *path=[self getFileUrl];
NSFileManager *fm = [[NSFileManager alloc] init];
if ([fm fileExistsAtPath:path]) {
_history = [d objectForKey:#"stringKey"];
class=[d objectForKey: #"ArrayKey"];
}
NSDictionary *d;
However the values are not getting initialized as per the plist. Is it the way I am extracting the values from the dictionary?
here is my function that saving json into plist in nscachesdirectory
-(void)saveproducts{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString* plistPath = [documentsPath stringByAppendingPathComponent:#"Products.plist"];
NSDictionary*dict = [NSDictionary dictionary];
NSMutableArray *types = [NSMutableArray array];
NSArray *dictArray = [NSArray array];
NSArray *dictKeys = [NSArray array];
NSArray *productObjects = [NSArray array];
NSArray *productKeys = [NSArray array];
for (int i=0; i<appDelegate.products.count; i++) {
NSMutableArray *tmpProds = [NSMutableArray array];
NSString *t_ID = [[appDelegate.products objectAtIndex:i] valueForKey:#"id"];
NSString *t_image = [[appDelegate.products objectAtIndex:i] valueForKey:#"image"];
NSString *t_name =[[appDelegate.products objectAtIndex:i] valueForKey:#"name"];
NSArray *products = [[appDelegate.products objectAtIndex:i] valueForKey:#"products"];
NSDictionary *productsDict = [NSDictionary dictionary];
for (int j=0; j<products.count; j++) {
NSString *p_id = [[products objectAtIndex:j] valueForKey:#"id"];
NSString *p_name = [[products objectAtIndex:j] valueForKey:#"name"];
NSString *p_name2 = [[products objectAtIndex:j] valueForKey:#"name2"];
NSString *image = [[products objectAtIndex:j] valueForKey:#"image"];
NSString *typeID = [[products objectAtIndex:j] valueForKey:#"type_id"];
NSString *active = [[products objectAtIndex:j] valueForKey:#"active"];
NSString *available = [[products objectAtIndex:j] valueForKey:#"available"];
NSString *desc = [[products objectAtIndex:j] valueForKey:#"description"];
NSString *price = [[products objectAtIndex:j] valueForKey:#"price"];
if ([p_name2 isEqual:[NSNull null]]) {
p_name2 =#"undefined";
}
if ([desc isEqual:[NSNull null]]) {
desc = #"";
}
productObjects = [NSArray arrayWithObjects:p_id,p_name,p_name2,image,typeID,active,available,desc,price, nil];
productKeys = [NSArray arrayWithObjects:#"id",#"name",#"name2",#"image",#"type_id",#"active",#"available",#"desc",#"price", nil];
productsDict = [NSDictionary dictionaryWithObjects:productObjects forKeys:productKeys];
[tmpProds addObject:productsDict];
if (![image isEqualToString:#""]) {
[foodImages addObject:image];
}
}
dictArray = [NSArray arrayWithObjects:t_ID,t_image,t_name,tmpProds, nil];
dictKeys = [NSArray arrayWithObjects:#"id",#"image",#"name",#"products", nil];
dict = [NSDictionary dictionaryWithObjects:dictArray forKeys:dictKeys];
[types addObject:dict];
}
NSDictionary* plistDict = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects:types, nil] forKeys:[NSArray arrayWithObjects:#"ptype", nil]];
NSString *error = nil;
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
if(plistData)
{
[plistData writeToFile:plistPath atomically:YES];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setBool:YES forKey:#"cached"];
[defaults synchronize];
}
else
{
NSLog(#"Error log: %#", error);
}
}
and this one reading plist
-(void)loadFromplist{
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString* plistPath = [documentsPath stringByAppendingPathComponent:#"Products.plist"];
NSData *plistData = [[NSFileManager defaultManager] contentsAtPath:plistPath];
NSDictionary *dict = (NSDictionary*)[NSPropertyListSerialization propertyListFromData:plistData mutabilityOption:NSPropertyListMutableContainersAndLeaves format:nil errorDescription:nil];
productsArray = [dict valueForKey:#"ptype"];
[self.tableView reloadData];
}