micMac Solutions
micMac Solutions

Reputation: 3

I want to replace Json values to another string values in iOS

Using Json I have retrieve some values to UITableViewCell

NSString *sample = [[array objectAtIndex:indexPath.row] objectForKey:@"food"];

I am getting 1,2,3,4,6 in my sample string values

But I want to show like, if for example 1=apple 2=grape 3=orange 4=pineapple 5=lemon 6=All

I want the result to be apple,grape,orange,pineapple,All in my sample string values

Upvotes: 0

Views: 230

Answers (3)

partha_devArch
partha_devArch

Reputation: 454

Define a NSDictionary with your required mapping, and fetch the value from your mapping dictionary:

NSDictionary *foodDict = @{
  @"1": @"apple",
  @"2": @"grape",
  @"3": @"orange",
  @"4": @"pineapple",
  @"5": @"lemon",
  @"6": @"all"
};

NSString *sample = [[array objectAtIndex:indexPath.row] objectForKey:@"food"];

NSString *sampleValue= [foodDict valueForKey:sample];

"sampleValue" is your required String Value needed. (Cast it to NSString if required)

Upvotes: 0

Vinu Jacob
Vinu Jacob

Reputation: 381

Change your code objectForKey@"" to valueForKey@""

NSString *sample = [[array objectAtIndex:indexPath.row] valueForKey:@"food"];

Upvotes: 0

TheTiger
TheTiger

Reputation: 13354

In Objective-C there is no built in enums available for String types. You can declare enums as Integer and then make a function or an array of strings which return the string value for that enum.

Declare in your .h file.

typedef NS_ENUM(NSInteger, FRUIT) {
    APPLE = 1,
    GRAPE,
    ORANGE,
    PINEAPPLE,
    LEMON,
    All
};

extern NSString * const FRUITString[];

Define in your .m file.

NSString * const FRUITString[] = {
    [APPLE] = @"APPLE",
    [GRAPE] = @"GRAPE",
    [ORANGE] = @"ORANGE",
    [PINEAPPLE] = @"PINEAPPLE",
    [LEMON] = @"LEMON",
    [All] = @"All"
};

and you can use it like:

NSLog(@"%@", FRUITString[APPLE]);
// OR
NSLog(@"%@", FRUITString[1]);

Output: APPLE

Based on your comment: if food values is "food":"1,2" I want to show "apple,grape"

NSString *foodValue = @"1,2";
NSArray *values = [foodValue componentsSeparatedByString:@","];
NSMutableArray *stringValues = [[NSMutableArray alloc] init];
for (NSString *value in values) {
    [stringValues addObject:FRUITString[[value integerValue]]];
}
NSLog(@"%@", [stringValues componentsJoinedByString:@","]);

APPLE,GRAPE

Upvotes: 1

Related Questions