Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating nested JSON string using nsmutabledictionary

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?

like image 787
Siddharthan Asokan Avatar asked Oct 27 '13 03:10

Siddharthan Asokan


2 Answers

If you want this the best way is create more dictionary example:

NSMutableDictionary *json= [[NSMutableDictionary alloc] init];
[json setObject:@"4992" forKey:@"cat_id"];
[json setObject:@"Toshiba" forKey:@"brand"];
//create weight object
NSMutableDictionary *weight= [[NSMutableDictionary alloc] init];
[weight setObject:@"1000000" forKey:@"gte"];
[weight setObject:@"1500000" forKey:@"lt"];
//attach the object
[json setObject:weight forKey:@"weight"];
//create sitedetails objects
NSMutableDictionary *sitedetails= [[NSMutableDictionary alloc] init];
[sitedetails setObject:@"newegg.com" forKey:@"name"];
//create latestoffers objects
NSMutableDictionary *latestoffers= [[NSMutableDictionary alloc] init];
[latestoffers setObject:@"USD" forKey:@"currency"];
//new dictionary for price
[sitedetails setObject:latestoffers forKey:@"latestoffers"];
[json setObject:sitedetails forKey:@"sitedetails"];
NSLog(@"%@",json);

After you can convert dictionary in json string...

-(NSString*)getJsonStringByDictionary:(NSDictionary*)dictionary{
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary
                                                   options:NSJSONWritingPrettyPrinted
                                                     error:&error];
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
like image 129
Serluca Avatar answered Oct 23 '22 10:10

Serluca


Using the new Objective-C syntax and NSJSONSerialization, as pointed out by others, this can be done quite nicely:

NSDictionary *latestprice = @{@"gte": @100};
NSDictionary *latest = @{@"currency": @"USD", @"price": latestprice};
NSDictionary *details = @{@"name": @"newegg.com", @"latestoffers": latest};
NSDictionary *weight = @{@"gte": @1000000, @"lt": @1500000};
NSDictionary *json = @{
    @"cat_id": @4992,
    @"brand": @"Toshiba",
    @"weight": weight,
    @"sitedetails": details
};


NSData *data = [NSJSONSerialization dataWithJSONObject:json
                                               options:NSJSONWritingPrettyPrinted
                                                 error:nil];
NSString *jsonStr = [[NSString alloc] initWithData:data
                                          encoding:NSUTF8StringEncoding];

I don't know what your querybuild is, but if it is a dictionary you can just pull out the data as needed. Or do you need to dynamically create this structure, based on the keys in querybuild?

like image 7
Pascal Avatar answered Oct 23 '22 11:10

Pascal