2016-12-27 56 views
-2

我打电话给Web服务,它返回字典来呈现图形。字典结构是iOS - 使用动态密钥的JSONModel

{"1":0,"2":0,"8":0,"9":2,"10":3,"11":0,"12":0}

问题是关键是动态值如1,2,3等表示月份。是否有可能在JsonModel中表示这一点?

+2

问题实际上更多的是Objective-C不允许属性的名称是数字(甚至任何以数字开头的)。但是,你可以绝对操纵从JSON派生的字典而不使用JsonModel,只需使用'NSJSONSerialization JSONObjectWithData:options:error:'和访问返回的'NSDictionary'中的键。 – jcaron

+0

您的预期输出是什么 –

回答

0

看到你不能在运行时根据响应结构创建属性。但是我们可以巧妙地使用预定义的东西并实现这一点。请执行以下步骤:

创建一个模型类。所以,你MyCustomModel.h文件看起来像这样

#import <Foundation/Foundation.h> 

@interface MyCustomModel : NSObject 

@property (nonatomic, retain) NSString * myCustomKey; 
@property (nonatomic, retain) NSString * myCustomValue; 

@end 

这将是你MyCustomModel.m文件

#import "MyCustomModel.h" 

@implementation MyCustomModel 
@synthesize myCustomKey, myCustomValue; 

-(id)init { 
    self = [super init]; 

    myCustomKey = @""; 
    myCustomValue = @""; 

    return self; 
} 
@end 

现在让我们假设{ “1”:0, “2”:0, “8”:0, “9”:2, “10”:3, “11”:0, “12”:0}是NSDictionary和让说它的名字是dictionaryResponse

现在为此充塞:

NSArray *responseKeys = [[NSArray alloc]init]; 
responseKeys = [dictionaryResponse allKeys]; 

因此,您的响应键将具有[[1,2,8,9,10,11,12,环和创建模型对象的NSMutableArray作为

NSMutableArray *arrayMonthList = [[NSMutableArray alloc]init]; 

for (int i = 0; i < responseKeys.count; i++) { 
    MyCustomModel *myModelObject = [[MyCustomModel alloc]init]; 
    myModelObject.myCustomKey = [NSString stringWithFormat:@"%@",[responseKeys objectAtIndex:i]]; 
    myModelObject.myCustomValue = [dictionaryResponse valueForKey:[NSString stringWithFormat:@"%@",[responseKeys objectAtIndex:i]]]; 
    [arrayMonthList addObject:myModelObject]; 
} 

现在arrayMonthList将由类型的对象MyCustomModel

所以,你可以使用它,分析它。即使你可以用它来显示UITableView。以下代码是为了打印模型属性的值而编写的,您可以根据您的预期水平进行自定义。

for (int i = 0; i < arrayMonthList.count; i++) { 
     MyCustomModel *myModelObject = [arrayMonthList objectAtIndex:i]; 
     NSLog(@"Month is %@ and its value is %@",myModelObject.myCustomKey,myModelObject.myCustomValue); 
    }