2016-12-27 5 views
-2

그래프를 렌더링하기 위해 사전을 반환하는 웹 서비스를 호출합니다. 사전 구조iOS - 동적 키가있는 JSONModel

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

문제는 키 개월 나타내는 1,2,3 등 같은 동적 값이다이다. JsonModel에서이를 표현할 수 있습니까?

+2

실제로 Objective-C는 속성에 숫자 (또는 숫자로 시작하는 이름)가있는 이름을 가질 수 없습니다. 하지만 JsonModel없이 JSON에서 파생 된 사전은 정확히 조작 할 수 있습니다. 단지 NSJSONSerialization JSONObjectWithData : options : error :'를 사용하고 반환 된 NSDictionary에서 액세스 키를 사용하면됩니다. – jcaron

+0

예상 출력은 얼마입니까? –

답변

0

응답 구조에 따라 런타임에 속성을 만들 수 없습니다. 그러나 미리 정의 된 것을 현명하게 사용하고이를 달성 할 수 있습니다. 다음 단계를 수행하십시오.

하나의 모델 클래스를 만듭니다. 0, "2": 0, "8"그래서 MyCustomModel.h 파일이 당신의 MyCustomModel.m 파일

#import "MyCustomModel.h" 

@implementation MyCustomModel 
@synthesize myCustomKey, myCustomValue; 

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

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

    return self; 
} 
@end 

이제 수 있습니다 가정하자 { "1"이됩니다이

#import <Foundation/Foundation.h> 

@interface MyCustomModel : NSObject 

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

@end 

모양을 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 등]의 모든 키가 있습니다.

이제 반복 할 수 있습니다. 루프

그래서 당신이 그것을 사용하고 분석 할 수 MyCustomModel 이제 arrayMonthList 유형의 개체로 구성됩니다 모델 객체의 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]; 
} 

로 만들 수 있습니다. 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); 
    }