需要创建以下模型。
以下是来自Web服务响应的Json响应,
现在,我想创建它的模型,以便我们可以轻松地获取它,例如
EmployeeClass.status =
EmployeeClass.statusCode =
EmployeeClass.description =
EmployeeClass.employeeId =
EmployeeClass.Present =
EmployeeClass.Leave =
EmployeeClass.Absent =
EmployeeClass.PFCode=
我的JSON字符串是
{
"EmployeeClass": {
"responseStatus": {
"status": "SUCCESS",
"statusCode": "100",
"description": "Success",
"employeeId": "1011"
},
"Present": 22,
"Leave": 1,
"Absent": 4
},
"PFCode": "ABC123"
}
到目前为止我尝试过的
创建单例类EmployeeClass
//------.h class ----------------
#import < Foundation/Foundation.h >
@interface EmployeeClass : NSObject
@property (nonatomic, strong)NSString * status ;
@property (nonatomic, strong)NSString * statusCode ;
@property (nonatomic, strong)NSString * description ;
@property (nonatomic, strong)NSString * employeeId ;
@property (nonatomic, strong)NSString * Present ;
@property (nonatomic, strong)NSString * Leave ;
@property (nonatomic, strong)NSString * Absent ;
@property (nonatomic, strong)NSString * PFCode;
+ (EmployeeClass*)sharedSingleton;
@end
//----------.m类-----------
#import "EmployeeClass.h"
@implementation EmployeeClass
- (id)init {
self = [super init];
if(self) {
self.status = [NSString new];
self.statusCode = [NSString new];
self.description = [NSString new];
self.employeeId = [NSString new];
self.Present = [NSString new];
self.Leave = [NSString new];
self.Absent = [NSString new];
self.PFCode = [NSString new];
//do any more customization to your location manager
}
return self;
}
+ (EmployeeClass *)sharedSingleton {
static EmployeeClass *sharedSingleton;
@synchronized(self) {
if (sharedSingleton == nil) {
sharedSingleton = [[EmployeeClass alloc] init];
}
}
return sharedSingleton;
}
@end
最佳答案
我不知道我是否正确理解了您的问题,但是您不应该执行EmployeeClass.property =
之类的操作,因为您正试图访问存储在CLASS中的某些属性,但这没有任何意义。您必须访问该类的实例。
因此,首先您必须检索单例的实例:EmployeeClass *obj = [EmployeeClass sharedSingleton];
,然后可以访问对象的属性:obj.status =
要解析JSON字符串,您可以执行以下操作:
NSError *error;
NSData *jsondata = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary respObj = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
因此,现在您有了包含所有属性的字典。要访问单个属性:
[respObj valueForKey:@"anyKey"];
。例如obj.status = [respObj valueForKey:@"EmployeeClass"] valueForKey:@"responseStatus"] valueForKey:@"status"]
。这是因为第一个和第二个“ valueForKey”消息将返回另一个NSDictionary。希望这可以帮助。