iOS数据解析

  • 从服务器获取数据之后,接下来我们就需要对数据进行解析,转换成模型;有时候数据比较复杂,搞得我头晕脑胀的,就记录一下
  • 数据是这样的


    数据样式.png
  • 取出 templist 数组里面的字典,然后字典里面又有一个数组 Labels
  • 创建两个模型,一个是 templist 里面的字典的模型,另外一个是字典里面的的Labels的字典里面的模型
#import <Foundation/Foundation.h>

@interface ModelLabel : NSObject

@property (nonatomic, copy) NSString *content;
@property (nonatomic, copy) NSString *fontcolor;
@property (nonatomic, copy) NSString *bgcolor;

+(instancetype)modelWithDict:(NSDictionary *)dict;

@end
#import "ModelLabel.h"

@implementation ModelLabel

+(instancetype)modelWithDict:(NSDictionary *)dict{
    return [[self alloc] initWithDict:dict];
}

-(instancetype)initWithDict:(NSDictionary *)dict{
    if (self = [super init]) {
        [self setValuesForKeysWithDictionary:dict];
    }
    return self;
}

-(void)setValue:(id)value forUndefinedKey:(NSString *)key{
    
}

@end

.h
#import <Foundation/Foundation.h>
#import "ModelLabel.h"

@interface ModelList : NSObject

@property (nonatomic, copy) NSString *time_waitpost;
@property (nonatomic, copy) NSString *bizname;
@property (nonatomic, copy) NSString *bizaddress;
@property (nonatomic, copy) NSString *receiver_name;
@property (nonatomic, copy) NSString *receiver_address;
@property (nonatomic, copy) NSArray <ModelLabel *>*arrLabel;

+(instancetype)modelWithDict:(NSDictionary *)dict;

@end
.m
#import "ModelList.h"
@implementation ModelList

+(instancetype)modelWithDict:(NSDictionary *)dict{
    return [[self alloc] initWithDict:dict];
}

-(instancetype)initWithDict:(NSDictionary *)dict{
    if (self = [super init]) {
        [self setValuesForKeysWithDictionary:dict];
        NSMutableArray *arr = [NSMutableArray array];
        //取出Labels数组里面的数据转换成ModelLabel模型,如果是模型里面嵌套有其他模型,需要在这里调用其他模型的转模型方法
        NSArray *arrTemp = dict[@"Labels"];
        for (NSDictionary *dictTemp in arrTemp) {
            [arr addObject:[ModelLabel modelWithDict:dictTemp]];
        }
        self.arrLabel = [arr copy];
    }
    return self;
}

-(void)setValue:(id)value forUndefinedKey:(NSString *)key{
    
}

@end
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 在现在这个网络发达的时代里,要获取各种信息。我们会从网络获取XML或者JSON格式的数据,我们开发人员就要对它进行...
    MiracleGl阅读 2,197评论 2 184
  • 在iOS开发中,数据解析转化方面有许多比较好用的框架,如MjExtension,自己以前写过一个数据解析框架...
    iOS谢先森阅读 1,017评论 0 3
  • #pragma mark ****JSON数据解析**** 一、JSON解析 1、概念:Javaacript ob...
    磊CC阅读 319评论 0 1
  • 所谓"解析":从事先规定好的格式中提取数据解析一共有两种格式:JSON和XML一、JSON全称JavaScript...
    cj2527阅读 833评论 1 1
  • +(NSArray*)allLists { NSMutableArray*newlists = [NSMutabl...
    JakieZhang阅读 188评论 0 0