Reputation: 398
I want to create a model class for the json. My JSON example is given below
json response from API:
msg = '{"type":"TYPE_NM","payload":{"responseCode":0,"nextCheckTime":30}}';
I want to create a codable(Swift) properties is like in Objective-C.
I have created two nsobject interfaces as "type" and "payload". Below I am giving my class snippets.
//msg model
@interface MessageModel : NSObject
@property (nonatomic) NSString *type;
@property (nonatomic) Payload *payload;
@end
//for payload
@interface Payload : NSObject
@property (nonatomic) NSUInteger responseCode;
@property (nonatomic) NSUInteger nextCheckTime;
@end
Upvotes: 0
Views: 45
Reputation: 12154
You can convert json string to NSDictionary
object and use it to create MessageModel
Payload
@interface Payload : NSObject
@property (nonatomic) NSUInteger responseCode;
@property (nonatomic) NSUInteger nextCheckTime;
@end
@implementation Payload
- (instancetype)initWithDictionary:(NSDictionary *)dict {
self = [super init];
if (self) {
_responseCode = [dict[@"responseCode"] integerValue];
_nextCheckTime = [dict[@"nextCheckTime"] integerValue];
}
return self;
}
@end
MessageModel
@interface MessageModel : NSObject
@property (nonatomic) NSString *type;
@property (nonatomic) Payload *payload;
@end
@implementation MessageModel
- (instancetype)initWithDictionary:(NSDictionary *)dict {
self = [super init];
if (self) {
_type = dict[@"type"];
_payload = [[Payload alloc] initWithDictionary:dict[@"payload"]];
}
return self;
}
- (instancetype)initWithJson:(NSString *)json {
self = [super init];
if (self) {
NSData *data = [json dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
_type = dict[@"type"];
_payload = [[Payload alloc] initWithDictionary:dict[@"payload"]];
}
return self;
}
@end
Usage
NSString *input = @"{\"type\":\"TYPE_NM\",\"payload\":{\"responseCode\":0,\"nextCheckTime\":30}}";
MessageModel *model = [[MessageModel alloc] initWithJsonString:input];
Upvotes: 1