反射--> 解析JSON資料,反射--解析json

來源:互聯網
上載者:User

反射--> 解析JSON資料,反射--解析json

 

方法一Persons.json檔案
[ { "name": "Chris", "age": 18, "city": "Shanghai", "job": "iOS" }, { "name": "Ada", "age": 16, "city": "Beijing", "job": "student" }, { "name": "Rita", "age": 17, "city": "Xiamen", "job": "HR" } ]
 Model.h類
 1 #import <Foundation/Foundation.h> 2  3 @interface PersonModel : NSObject 4  5 @property (nonatomic, copy) NSString *name; 6 @property (nonatomic, assign) NSInteger age; 7 @property (nonatomic, copy) NSString *city; 8 @property (nonatomic, copy) NSString *job; 9 @property (nonatomic, copy) NSString *sex;10 11 - (instancetype)initWithNSDictionary:(NSDictionary *)dict;12 13 @end

 

Model.m類
 1 #import "PersonModel.h" 2 #import <objc/runtime.h> 3  4 @implementation PersonModel 5  6 - (instancetype)initWithNSDictionary:(NSDictionary *)dict { 7     self = [super init]; 8     if (self) { 9         [self prepareModel:dict];10     }11     return self;12 }13 14 - (void)prepareModel:(NSDictionary *)dict {15     NSMutableArray *keys = [[NSMutableArray alloc] init];16     17     u_int count = 0;18     objc_property_t *properties = class_copyPropertyList([self class], &count);19     for (int i = 0; i < count; i++) {20         objc_property_t property = properties[i];21         const char *propertyCString = property_getName(property);22         NSString *propertyName = [NSString stringWithCString:propertyCString encoding:NSUTF8StringEncoding];23         [keys addObject:propertyName];24     }25     free(properties);26     27     for (NSString *key in keys) {28         if ([dict valueForKey:key]) {29             [self setValue:[dict valueForKey:key] forKey:key];30         }31     }32 }33 34 @end

 

 

調用
1 NSString *file = [[NSBundle mainBundle] pathForResource:@"Persons" ofType:@"json"];2     NSData *data = [NSData dataWithContentsOfFile:file];3     NSMutableArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];4     5     for (NSDictionary *model in array) {6         PersonModel *person = [[PersonModel alloc] initWithNSDictionary:model];7         NSLog(@"%@, %ld, %@, %@", person.name, (long)person.age, person.city, person.job);8     }

 

 

列印結果:

 

 

 

 

方法二

資料模型的父類是:JSONModel

JSONModel的子類是:JSONPerson, JSONStudent, JSONTeacther等;

JSONStudent.h中
 1 @import JSONModel; 2  3 @interface JSONStudent : JSONModel 4  5 @property (nonatomic, copy) NSString * id; 6 @property (nonatomic, copy) NSString * name; 7 @property (nonatomic, copy) NSString * nickName; 8 @property (nonatomic, copy) NSString * phoneNumber; 9 10 @end

 

 

注意:這是用OC來寫的!

 擷取屬性 
 1 func getAllProperties<T: JSONModel>(anyClass: T) -> [String] { 2         var properties = [String]() 3         let count = UnsafeMutablePointer<UInt32>.allocate(capacity: 0) 4         let buff = class_copyPropertyList(object_getClass(anyClass), count) 5         let countInt = Int(count[0]) 6          7         for i in 0..<countInt { 8             let temp = buff![i] 9             let tempPro = property_getName(temp)10             let proper = String(utf8String: tempPro!)11             properties.append(proper!)12         }13         return properties14         15     }

 

注意:擷取屬性使用Swift寫的,單純用Swift和OC要簡單!

使用
1 func returnListStudent(students: [JSONStudent]) {2         for item in students {3             let studentProperties = self.getAllProperties(anyClass: item)4             for i in 0..< studentProperties.count{5                 print("值是:\(item.value(forKey: studentProperties[I]))" + "屬性是:\(studentProperties[i])"self.dataError)6             }7         }8     }

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.