2016-12-27 23 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); 
    }