我正在尝试创建以下格式的 json 字符串:
{
"cat_id" : 4992,
"brand" : "Toshiba",
"weight" : { "gte":1000000, "lt":1500000 },
"sitedetails" : {
"name" : "newegg.com",
"latestoffers" : {
"currency": "USD",
"price" : { "gte" : 100 }
}
}
}
我使用以下方法来生成它:
-(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);
}
最终生成的 nsmutabledictionary 是:
querybuild {
brand = Toshiba;
"cat_id" = 4992;
sitedetails = {
gte = 100;
latestoffers = {
gte = 100;
price = {
gte = 100;
};
};
price = {
gte = 100;
};
};
weight = {
lt = 1500000;
};
}
我传递了对象和密钥,如下所示:
[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"];
关于如何生成所需输出的任何想法?querybuild 是在这个方法中声明为类变量的 nsmutabledictionary 对象吗?