I'm trying to create a json string of the below format:
{
"cat_id" : 4992,
"brand" : "Toshiba",
"weight" : { "gte":1000000, "lt":1500000 },
"sitedetails" : {
"name" : "newegg.com",
"latestoffers" : {
"currency": "USD",
"price" : { "gte" : 100 }
}
}
}
I used the following method to generate this:
-(void)queryBuilderWithObj:(NSString *)object andKeyValue:(NSString *)key{
NSLog(@"object %@ and key %@",object,key);
if([key rangeOfString:@","].location == NSNotFound){
[querybuild setObject:object forKey:key];
}else{
NSArray *tempArray = [key componentsSeparatedByString:@","];
int index = tempArray.count - 1;
NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] init];
while (index) {
if (index == tempArray.count - 1) {
if([querybuild objectForKey:[tempArray objectAtIndex:index]]){
NSMutableArray *objArray = [[NSMutableArray alloc] init];
[objArray addObject:[querybuild objectForKey:[tempArray objectAtIndex:index]]];
[objArray addObject:object];
[tempDict setObject:objArray forKey:[tempArray objectAtIndex:index]];
}else{
[tempDict setObject:object forKey:[tempArray objectAtIndex:index]];
}
}else{
if([querybuild objectForKey:[tempArray objectAtIndex:index]]){
NSMutableArray *objArray = [[NSMutableArray alloc] init];
[objArray addObject:[querybuild objectForKey:[tempArray objectAtIndex:index]]];
NSMutableDictionary *subDict = [[NSMutableDictionary alloc] init];
[subDict setDictionary:tempDict];
[objArray addObject:subDict];
[tempDict setObject:objArray forKey:[tempArray objectAtIndex:index]];
}else{
NSMutableDictionary *subDict = [[NSMutableDictionary alloc] init];
[subDict setDictionary:tempDict];
[tempDict setObject:subDict forKey:[tempArray objectAtIndex:index]];
}
}
index --;
}
[querybuild setObject:tempDict forKey:[tempArray objectAtIndex:0]];
}
NSLog(@"querybuild %@ ",querybuild);
}
and the final nsmutabledictionary generated is:
querybuild {
brand = Toshiba;
"cat_id" = 4992;
sitedetails = {
gte = 100;
latestoffers = {
gte = 100;
price = {
gte = 100;
};
};
price = {
gte = 100;
};
};
weight = {
lt = 1500000;
};
}
I passed the object and key as below:
[sem queryBuilderWithObj:@"4992" andKeyValue:@"cat_id" ];
[sem queryBuilderWithObj:@"Toshiba" andKeyValue:@"brand"];
[sem queryBuilderWithObj:@"1000000" andKeyValue:@"weight,gte"];
[sem queryBuilderWithObj:@"1500000" andKeyValue:@"weight,lt"];
[sem queryBuilderWithObj:@"newegg.com"andKeyValue:@"sitedetails,name" ];
[sem queryBuilderWithObj:@"USD" andKeyValue:@"sitedetails,latestoffers,currency"];
[sem queryBuilderWithObj:@"100" andKeyValue:@"sitedetails,latestoffers,price,gte"];
Any idea on how to generate the required output? querybuild is the nsmutabledictionary object in this method declared as a class variable?