您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

Objective-C 中 JSON 轉模型的幾種做法:從 KVC 到 Runtime

編輯:iOS 開發綜合

日常開發離不開把 plist、json 之類的結構化資料轉成模型。Apple 提供了 KVC(Key-Value Coding)這個便利工具,但它有前提條件:模型的屬性數量不能少於字典的 key 數量,且屬性名稱必須與 key 完全一致。

一旦名稱對不上,KVC 就會直接拋出異常。本文示範如何在這種情況下完成轉換。

先看一個對不上的例子

模型定義:

@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *ID;

JSON 資料:

{
    "title" : "順平侯",
    "name" : "趙雲",
    "id" : "sph"
},
{
    "title" : "恆侯",
    "html" : "張飛",
    "id" : "hh"
}

問題很明顯:Objective-C 中 id 是關鍵字,所以屬性改名為 ID,但 JSON 裡仍是 id;另外部分資料用了 html 而非 name。這種情況下直接餵給 KVC 必定出錯。

方案一:先試著修補 KVC

在模型 .h 提供一個轉換用的類方法:

@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *ID;

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

實作:

+ (instancetype)itemWithDict:(NSDictionary *)dict {
    HeroItem *item = [[self alloc] init];

    [item setValuesForKeysWithDictionary:dict];

    return item;
}

setValuesForKeysWithDictionary: 會遍歷字典裡所有的 key,逐一呼叫 setValue:forKey:。所以我們要攔截的就是這個方法:

- (void)setValue:(id)value forKey:(NSString *)key {
    // 已知要替換的 key,直接判等即可
    if ([key isEqualToString:@"id"]) {
        [self setValue:value forKeyPath:@"ID"];
    } else {
        // 其餘交回父類處理
        [super setValue:value forKey:key];
    }
}

這樣 KVC 路線就能跑通了。但想想看:如果對不上的 key 有幾十個呢?每個模型都要重寫一次 setValue:forKey:,顯然不可行。

方案二:用 Runtime 反向遍歷模型

換個思路:與其遍歷字典去模型裡比對,不如遍歷模型的屬性,再回字典裡找對應的 key。這件事需要 Runtime。

#import <objc/runtime.h>

建立轉換方法,多傳一個「替換表」字典,用來描述「模型屬性名 → JSON key」的映射:

+ (instancetype)objcWithDict:(NSDictionary *)dict updateDict:(NSDictionary *)updateDict {
    id objc = [[self alloc] init];

    // 遍歷模型中的所有屬性
    unsigned int count = 0;
    Ivar *ivars = class_copyIvarList(self, &count);

    for (int i = 0; i < count; i++) {
        Ivar ivar = ivars[i];

        // 屬性名稱(去掉開頭的底線)
        NSString *ivarName = @(ivar_getName(ivar));
        ivarName = [ivarName substringFromIndex:1];

        id value = dict[ivarName];

        // 若字典中找不到同名 key,就去替換表查
        if (value == nil) {
            if (updateDict) {
                NSString *keyName = updateDict[ivarName];
                value = dict[keyName];
            }
        }

        [objc setValue:value forKeyPath:ivarName];
    }

    return objc;
}

呼叫端只要傳入替換表:

+ (instancetype)itemWithDict:(NSDictionary *)dict {
    // updateDict 中放需要替換的對應關係
    HeroItem *item = [HeroItem objcWithDict:dict updateDict:@{@"ID": @"id"}];
    return item;
}

兩個方案相比,第一種看起來簡單,但模型一多就得反覆重寫 setValue:;第二種可以完全封裝,任何模型都能共用,只是需要理解 Runtime 的 Ivar 遍歷。若是正式的大型專案,其實更推薦直接採用成熟的三方庫,例如 MJExtension,寫起來輕ver本,維護成本也低。

另一個選擇:Jastor

如果你手邊已有 Jastor 這個庫,事情會更簡單。基本用法如下。

讓模型繼承 Jastor:

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

@interface DeviceEntity : Jastor

@property (nonatomic, strong) NSNumber *isonline;
@property (nonatomic, strong) NSNumber *isopen;
@property (nonatomic, copy)   NSString *brand;

@end
#import "DeviceEntity.h"

@implementation DeviceEntity

@synthesize isopen, isonline, brand;

@end

支援巢狀與陣列屬性:

#import <Foundation/Foundation.h>
#import "Jastor.h"
#import "DeviceEntity.h"

@interface UserDevicesEntity : Jastor

@property (nonatomic, strong) NSNumber *closecount;
@property (nonatomic, strong) NSNumber *opencount;
@property (nonatomic, copy)   NSString *success;
@property (nonatomic, strong) NSArray  *items;

@end
#import "UserDevicesEntity.h"
#import "DeviceEntity.h"

@implementation UserDevicesEntity

@synthesize closecount, opencount, success, items;

+ (Class)items_class {
    return [DeviceEntity class];
}

@end

這裡有兩個關鍵點:基本型別要用 NSNumber 包裝;陣列屬性必須實作一個「屬性名 + _class」的類方法,告訴 Jastor 陣列裡放的是什麼型別,這一步寫錯就會解析失敗。

使用時,先把 JSON 字串轉成 NSDictionary,再交給模型初始化:

NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                              @"1", @"isonline",
                              @"1", @"isopen",
                              @"brand1", @"brand", nil];

DeviceEntity *device = [[DeviceEntity alloc] initWithDictionary:dictionary];

驗證一下:

NSLog(@"device's brand is %@", device.brand);
NSLog(@"device's isonline is %d", [device.isonline intValue]);
NSLog(@"device's isopen is %d", [device.isopen intValue]);

輸出:

2014-02-17 22:36:37.602 objc-grammar-learing[819:f803] device's brand is brand1
2014-02-17 22:36:37.605 objc-grammar-learing[819:f803] device's isonline is 1
2014-02-17 22:36:37.605 objc-grammar-learing[819:f803] device's isopen is 1

相較於逐欄手動解析字串,這方式清爽太多。上面只是最簡單的模型,真實專案還會有一對一、一對多等巢狀結構,官方文件都有對應範例可參考。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved