栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

iOS:通常从NSObject类序列化/反序列化复杂的JSON

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

iOS:通常从NSObject类序列化/反序列化复杂的JSON

最后,我们可以使用JSONModel轻松解决此问题。这是迄今为止最好的方法。JSONModel是一个库,该库通常基于Class序列化/反序列化您的对象。你甚至可以使用基于像财产上的非NSObject的

int
short
float
。它还可以满足嵌套复杂的JSON。

1)反序列化示例 。通过参考上面的示例,在头文件中:

#import "JSONModel.h"@interface Person : JSonModel @property (nonatomic, strong) NSString *firstName;@property (nonatomic, strong) NSString *lastName;@property (nonatomic, strong) NSNumber *age;@end@protocol Person;@interface Department : JSONModel@property (nonatomic, strong) NSMutableArray<Person> *accounting;@property (nonatomic, strong) NSMutableArray<Person> *sales;@end

在实现文件中:

#import "JSONModelLib.h"#import "myJSONClass.h"NSString *responseJSON = ;Department *department = [[Department alloc] initWithString:responseJSON error:&err];if (!err){    for (Person *person in department.accounting) {        NSLog(@"%@", person.firstName);        NSLog(@"%@", person.lastName);        NSLog(@"%@", person.age);  }    for (Person *person in department.sales) {        NSLog(@"%@", person.firstName);        NSLog(@"%@", person.lastName);        NSLog(@"%@", person.age);  }}

2)序列化示例 。在实现文件中:

#import "JSONModelLib.h"#import "myJSONClass.h"Department *department = [[Department alloc] init];Person *personAcc1 = [[Person alloc] init];personAcc1.firstName = @"Uee";personAcc1.lastName = @"Bae";personAcc1.age = [NSNumber numberWithInt:22];[department.accounting addOject:personAcc1];Person *personSales1 = [[Person alloc] init];personSales1.firstName = @"Sara";personSales1.lastName = @"Jung";personSales1.age = [NSNumber numberWithInt:20];[department.sales addOject:personSales1];NSLog(@"%@", [department toJSONString]);

这是来自Serialize示例的NSLog结果:

{ "accounting" : [{ "firstName" : "Uee","lastName"  : "Bae",         "age"       : 22 }      ],        "sales"      : [{ "firstName" : "Sara",          "lastName"  : "Jung",         "age"       : 20 }       ]}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/371994.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号