【问题标题】:create Model class to parse without any library创建模型类以在没有任何库的情况下进行解析
【发布时间】:2018-04-26 10:44:42
【问题描述】:

我想为 json 创建一个模型类。 下面给出了我的 JSON 示例

来自 API 的 json 响应:

msg = '{"type":"TYPE_NM","payload":{"responseCode":0,"nextCheckTime":30}}';

我想创建一个可编码(Swift)的属性,就像在 Objective-C 中一样。

我创建了两个 nsobject 接口作为“type”和“payload”。下面我给我的课sn-ps。

      //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

【问题讨论】:

    标签: objective-c json parsing model


    【解决方案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
    

    消息模型

    @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];
    

    【讨论】:

      猜你喜欢
      • 2014-02-02
      • 1970-01-01
      • 2019-09-28
      • 2018-02-14
      • 2012-03-23
      • 1970-01-01
      • 1970-01-01
      • 2010-09-08
      相关资源
      最近更新 更多