我想为json创建一个模型类。 我的JSON示例如下所示
来自API的json回复:msg =' {"输入":" TYPE_NM","有效负载":{" responseCode":0,& #34; nextCheckTime":30}}&#39 ;;
我想创建一个可编码(Swift)属性,就像在Objective-C中一样。
我创建了两个nsobject接口作为" type"和"有效载荷"。下面我给我的课堂片段。
//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
答案 0 :(得分:1)
您可以将json字符串转换为NSDictionary
对象并使用它来创建MessageModel
<强> 有效载荷 强>
@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
<强> 用法 强>
NSString *input = @"{\"type\":\"TYPE_NM\",\"payload\":{\"responseCode\":0,\"nextCheckTime\":30}}";
MessageModel *model = [[MessageModel alloc] initWithJsonString:input];