iOS:通常从NSObject类序列化/反序列化复杂的JSON
有人知道如何基于NSObject类序列化嵌套JSON吗?有序列化JSON简单的讨论在这里,但它不是一般的足够,以满足复杂的嵌套JSON。
想象这是JSON的结果:
{ "accounting" : [{ "firstName" : "John", "lastName" : "Doe",
"age" : 23 },
{ "firstName" : "Mary",
"lastName" : "Smith",
"age" : 32 }
],
"sales" : [{ "firstName" : "Sally",
"lastName" : "Green",
"age" : 27 },
{ "firstName" : "Jim",
"lastName" : "Galley",
"age" : 41 }
]}
从这个班级:
@interface Person : NSObject{}@property (nonatomic, span) NSString *firstName;
@property (nonatomic, span) NSString *lastName;
@property (nonatomic, span) NSNumber *age;
@end
@interface Department : NSObject{}
@property (nonatomic, span) NSMutableArray *accounting; //contain Person class
@property (nonatomic, span) NSMutableArray *sales; //contain Person class
@end
如何基于类对它们进行序列化/反序列化?
目前,我可以基于任何类生成这样的有效负载:
NSMutableDictionary *Payload = [self serialize:objClass];
但是它不能满足嵌套的复杂JSON的要求。有人对此有更好的解决方案吗?该
C#库可根据对象类进行序列化/反序列化。我想基于NSObject复制相同的东西
回答:
最后,我们可以使用JSONModel轻松解决此问题。这是迄今为止最好的方法。JSONModel是一个库,该库通常基于Class序列化/反序列化您的对象。你甚至可以使用基于像财产上的非NSObject的int
,short
和float
。它还可以满足嵌套复杂的JSON。
。通过参考上面的示例,在头文件中:
#import "JSONModel.h"@interface Person : JSONModel
@property (nonatomic, span) NSString *firstName;
@property (nonatomic, span) NSString *lastName;
@property (nonatomic, span) NSNumber *age;
@end
@protocol Person;
@interface Department : JSONModel
@property (nonatomic, span) NSMutableArray<Person> *accounting;
@property (nonatomic, span) NSMutableArray<Person> *sales;
@end
在实现文件中:
#import "JSONModelLib.h"#import "myJSONClass.h"
NSString *responseJSON = /*from example*/;
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);
}
}
。在实现文件中:
#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 }
]}
以上是 iOS:通常从NSObject类序列化/反序列化复杂的JSON 的全部内容, 来源链接: utcz.com/qa/406302.html