美文网首页
iOS中将Json字符串转为对象

iOS中将Json字符串转为对象

作者: J_xs | 来源:发表于2017-11-06 20:57 被阅读20次

--
layout: blog
title: 'iOS中将Json字符串转为对象'
date: 2017-05-02 12:11:34
categories: blog
tags: code
image: ''
lead-text: 'iOS中Json字符串转为对象'


iOS中将Json字符串转为对象

好久没写iOS了,在转Json的时候就完全忘记了怎么转Json了,所以记录一下,贴一段以前写的代码

*.h文件中声明两个方法,用来将Json字典转换为对象-简单对象,对象中不包含list等复杂数据结构且不包含子类</br>

/* *.h文件,创建两个方法,将传入的字典返回为对象 */
@interface SearchHotWord : NSObject

@property (nonatomic, copy) NSString *code;
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) NSInteger wordId;


- (instancetype)initWithDict:(NSDictionary *)dict;
+ (instancetype)searchHotWordWithDict:(NSDictionary *)dict;

@end

/* *.m文件,使用kvo设置对应的对象和dict中的value值,注意的是这里</br>如果key的值和dict中的key不一样,那么需要在forUndefinedKey方法中将</br>对应的key进行关联 */
@implementation SearchHotWord

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


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

- (void)setValue:(id)value forUndefinedKey:(NSString *)key{
    if ([key isEqualToString:@"id"]) {
        _wordId = [value integerValue];
    }
}

//- (void)setValue:(id)value forUndefinedKey:(NSString *)key
//{
//    if ([key isEqualToString:@"id"]) { // id重名,用这个方法避免
//        _wordId = value;
//    }
//}

@end

复杂对象转换,包含list等复杂结构和子类对象,使用mj的转换方式

/* *.h文件,有两个复杂对象,其中一个是一个可变array中包含一个对象*/
@property (nonatomic, strong) SingerInfo *singerinfo;
@property (nonatomic, assign) NSInteger songcount;
@property (nonatomic, strong) NSMutableArray<SearchSong *> *songlist;

/* *.m文件,使用mj的引用对对象进行解释,只需要对可变array中的对象进行解释,其他的非嵌套对象不需要*/

+ (NSDictionary *)mj_objectClassInArray{
    return @{
             @"songlist" : @"SearchSong"
             };
}

相关文章

网友评论

      本文标题:iOS中将Json字符串转为对象

      本文链接:https://www.haomeiwen.com/subject/zprrmxtx.html