JSON 數據的系統解析

- (IBAction)jsonSystemButtonDidClicked:(UIButton *)sender {

    self.JSONArray = [NSMutableArray array];

    // 1、拿到 json 文件的路徑
    NSString *path = [[NSBundle mainBundle] pathForResource:@"student" ofType:@"json"];

    // 2、根據路徑獲取文件內容爲 NSData 對象
    NSData *data = [NSData dataWithContentsOfFile:path];

    // 3、解析開始
    NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];


    for (NSDictionary *dict in array) {
        StudentModal *modal = [StudentModal new];
        [modal setValuesForKeysWithDictionary:dict];
        [self.JSONArray addObject:modal];
    }

    for (StudentModal *modal in self.JSONArray) {
        NSLog(@"JSONArray = %@, %ld, %@", modal.name, modal.number, modal.hobby);
    }
}
@property (nonatomic, strong) NSMutableArray *JSONArray;

當模型中類型衝突時

@implementation StudentModal

- (NSString *)description
{
    return [NSString stringWithFormat:@"%@, %@, %@, %ld, %@", self.name, self.sex,self.phoneNumber, self.number, self.hobby
            ];
}

- (void)setValue:(id)value forKey:(NSString *)key
{
    // super 必須寫
    [super setValue:value forKey:key];
    if ([key isEqualToString:@"number"]) {
        self.number = [value integerValue];
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章