iOS中JSONModel的使用

流弊的JSON數(shù)據(jù)模型框架

https://github.com/jsonmodel/jsonmodel

版本 1.3.0


如果你喜歡JSONModel,并且使用了它,請(qǐng)你:

  • star一下

  • 給我一些反饋. 多謝!


JSONModel for iOS and OSX

JSONModel 是一個(gè)能夠快速巧妙的創(chuàng)建數(shù)據(jù)模型的庫. 你可以在 iOS or OSX APP中使用它.

JSONModel 自動(dòng)檢查JOSN模型和結(jié)構(gòu)體, 徹底的減少你的代碼量.


添加JSONModel到你的項(xiàng)目中

要求

  • 支持持ARC; iOS 5.0+ / OSX 10.7+
  • SystemConfiguration.framework

as: 1) 源文件

1.下載JSONModel.zip文件
2.將它拷貝到你的項(xiàng)目中
3.導(dǎo)入SystemConfiguration.framework框架

or 2)使用 CocoaPods

pod 'JSONModel'

如果你想關(guān)于CocoaPods了解更多,請(qǐng)參考這個(gè)簡(jiǎn)單的教程.

or 3) 使用 Carthage

在你的項(xiàng)目的Cartfile添加JSONModel:

github "jsonmodel/jsonmodel"

文檔

你可以查看在線閱讀文檔: http://cocoadocs.org/docsets/JSONModel


基本使用

涉想你的JSON數(shù)據(jù)像這樣:

{ "id": "10", "country": "Germany", "dialCode": 49, "isInEurope": true }
  • 為你的數(shù)據(jù)模型創(chuàng)建一個(gè)Objective-C的類,繼承自JSONModel.
  • 將JSON中的keys在.h文件中聲明為屬性:
#import "JSONModel.h"

@interface CountryModel : JSONModel

@property (assign, nonatomic) int id;
@property (strong, nonatomic) NSString* country;
@property (strong, nonatomic) NSString* dialCode;
@property (assign, nonatomic) BOOL isInEurope;

@end

在.m文件中不需要做任何事情.

  • 用數(shù)據(jù)初始化你的model:
#import "CountryModel.h"
...

NSString* json = (fetch here JSON from Internet) ...
NSError* err = nil;
CountryModel* country = [[CountryModel alloc] initWithString:json error:&err];

如果傳過來的JSON合法,你所定義的所有的屬性都會(huì)與該JSON的值想對(duì)應(yīng),甚至JSONModel會(huì)嘗試去轉(zhuǎn)換數(shù)據(jù)為你期望的類型,如上所示:

  • 轉(zhuǎn)換id,從字符串轉(zhuǎn)換為int
  • 只需要拷貝一下country的值
  • 轉(zhuǎn)換diaCode,從number轉(zhuǎn)換為字符串
  • 最后一個(gè)是將isInEurope轉(zhuǎn)換為BOOL屬性

所以,你所需要做的就是將你的屬性定義為期望的類型.


在線教程

官方網(wǎng)站: http://www.jsonmodel.com

在線文檔: http://jsonmodel.com/docs/

傻瓜教程:


舉個(gè)栗子

命名自動(dòng)匹配

{
  "id": "123",
  "name": "Product name",
  "price": 12.95
}
@interface ProductModel : JSONModel
@property (assign, nonatomic) int id;
@property (strong, nonatomic) NSString* name;
@property (assign, nonatomic) float price;
@end

@implementation ProductModel
@end

模型嵌套 (模型包含其他模型)

{
  "order_id": 104,
  "total_price": 13.45,
  "product" : {
    "id": "123",
    "name": "Product name",
    "price": 12.95
  }
}

@interface OrderModel : JSONModel
@property (assign, nonatomic) int order_id;
@property (assign, nonatomic) float total_price;
@property (strong, nonatomic) ProductModel* product;
@end

@implementation OrderModel
@end

模型集合

{
  "order_id": 104,
  "total_price": 103.45,
  "products" : [
    {
      "id": "123",
      "name": "Product #1",
      "price": 12.95
    },
    {
      "id": "137",
      "name": "Product #2",
      "price": 82.95
    }
  ]
}
@protocol ProductModel
@end
@interface ProductModel : JSONModel
@property (assign, nonatomic) int id;
@property (strong, nonatomic) NSString* name;
@property (assign, nonatomic) float price;
@end

@implementation ProductModel
@end

@interface OrderModel : JSONModel
@property (assign, nonatomic) int order_id;
@property (assign, nonatomic) float total_price;
@property (strong, nonatomic) NSArray<ProductModel>* products;
@end

@implementation OrderModel
@end

注意: 尖括號(hào)后 <code>NSArray</code> 包含一個(gè)協(xié)議. 這跟Objective-C原生的泛型不是一個(gè)概念. 他們不會(huì)沖突, 但對(duì)于JSONModel來說,協(xié)議必須在一個(gè)地方聲明.

key映射

{
  "order_id": 104,
  "order_details" : [
    {
      "name": "Product#1",
      "price": {
        "usd": 12.95
      }
    }
  ]
}

@interface OrderModel : JSONModel
@property (assign, nonatomic) int id;
@property (assign, nonatomic) float price;
@property (strong, nonatomic) NSString* productName;
@end

@implementation OrderModel

+(JSONKeyMapper*)keyMapper
{
  return [[JSONKeyMapper alloc] initWithDictionary:@{
    @"order_id": @"id",
    @"order_details.name": @"productName",
    @"order_details.price.usd": @"price"
  }];
}

@end

設(shè)置全局鍵映射(應(yīng)用于所有model)

[JSONModel setGlobalKeyMapper:[
    [JSONKeyMapper alloc] initWithDictionary:@{
      @"item_id":@"ID",
      @"item.name": @"itemName"
   }]
];

設(shè)置下劃線自動(dòng)轉(zhuǎn)駝峰

{
  "order_id": 104,
  "order_product" : @"Product#1",
  "order_price" : 12.95
}
@interface OrderModel : JSONModel

@property (assign, nonatomic) int orderId;
@property (assign, nonatomic) float orderPrice;
@property (strong, nonatomic) NSString* orderProduct;

@end

@implementation OrderModel

+(JSONKeyMapper*)keyMapper
{
  return [JSONKeyMapper mapperFromUnderscoreCaseToCamelCase];
}

@end

可選屬性 (就是說這個(gè)屬性可以為null或者為空)

{
  "id": "123",
  "name": null,
  "price": 12.95
}
@interface ProductModel : JSONModel
@property (assign, nonatomic) int id;
@property (strong, nonatomic) NSString<Optional>* name;
@property (assign, nonatomic) float price;
@property (strong, nonatomic) NSNumber<Optional>* uuid;
@end

@implementation ProductModel
@end

忽略屬性 (就是完全忽略這個(gè)屬性)

{
  "id": "123",
  "name": null
}
@interface ProductModel : JSONModel
@property (assign, nonatomic) int id;
@property (strong, nonatomic) NSString<Ignore>* customProperty;
@end

@implementation ProductModel
@end

設(shè)置所有的屬性為可選(所有屬性值可以為空)

@implementation ProductModel
+(BOOL)propertyIsOptional:(NSString*)propertyName
{
  return YES;
}
@end

使用JSONModel自帶的 HTTP 請(qǐng)求


//add extra headers
[[JSONHTTPClient requestHeaders] setValue:@"MySecret" forKey:@"AuthorizationToken"];

//make post, get requests
[JSONHTTPClient postJSONFromURLWithString:@"http://mydomain.com/api"
                                   params:@{@"postParam1":@"value1"}
                               completion:^(id json, JSONModelError *err) {

                                   //check err, process json ...

                               }];

將model轉(zhuǎn)化為字典或者json格式的字符串


ProductModel* pm = [[ProductModel alloc] initWithString:jsonString error:nil];
pm.name = @"Changed Name";

//convert to dictionary
NSDictionary* dict = [pm toDictionary];

//convert to text
NSString* string = [pm toJSONString];

自定義數(shù)據(jù)的轉(zhuǎn)換


@implementation JSONValueTransformer (CustomTransformer)

- (NSDate *)NSDateFromNSString:(NSString*)string {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:APIDateFormat];
    return [formatter dateFromString:string];
}

- (NSString *)JSONObjectFromNSDate:(NSDate *)date {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:APIDateFormat];
    return [formatter stringFromDate:date];
}

@end

自定義處理指定的屬性


@interface ProductModel : JSONModel
@property (assign, nonatomic) int id;
@property (strong, nonatomic) NSString* name;
@property (assign, nonatomic) float price;
@property (strong, nonatomic) NSLocale *locale;
@end

@implementation ProductModel

// Convert and assign the locale property
- (void)setLocaleWithNSString:(NSString*)string {
    self.locale = [NSLocale localeWithLocaleIdentifier:string];
}

- (NSString *)JSONObjectForLocale {
    return self.locale.localeIdentifier;
}

@end

自定義JSON校驗(yàn)


@interface ProductModel : JSONModel
@property (assign, nonatomic) int id;
@property (strong, nonatomic) NSString* name;
@property (assign, nonatomic) float price;
@property (strong, nonatomic) NSLocale *locale;
@property (strong, nonatomic) NSNumber <Ignore> *minNameLength;
@end

@implementation ProductModel

- (BOOL)validate:(NSError *__autoreleasing *)error {
    BOOL valid = [super validate:error];

    if (self.name.length < self.minNameLength.integerValue) {
        *error = [NSError errorWithDomain:@"me.mycompany.com" code:1 userInfo:nil];
        valid = NO;
    }

    return valid;
}

@end

  • 錯(cuò)誤處理
  • 自定義數(shù)據(jù)校驗(yàn)
  • 自動(dòng)比較和相等判斷
  • 更多.

Misc

作者: Marin Todorov

參與者: Christian Hoffmann, Mark Joslin, Julien Vignali, Symvaro GmbH, BB9z.
任何人都可以 pull requests.

更新log : https://github.com/jsonmodel/jsonmodel/blob/master/CHANGELOG.md

Utility to generate JSONModel classes from JSON data: https://github.com/dofork/json2object


許可

This code is distributed under the terms and conditions of the MIT license.


參考指南

NB! 如果你解決了你發(fā)現(xiàn)的某個(gè)BUG, 請(qǐng)?zhí)砑訂卧獪y(cè)試,這樣以便我在合并之前復(fù)現(xiàn)這個(gè)BUG.


使用問題匯總

1、1.4.0版本的JSONKeyMapper

如果需要替換服務(wù)端返回來的key,需要按照下面的結(jié)構(gòu)@{@"你的key":@"接口返回的key"},并且請(qǐng)使用initWithModelToJSONDictionary這個(gè)方法。

+ (JSONKeyMapper *)keyMapper {
    return [[JSONKeyMapper alloc] initWithModelToJSONDictionary:
            @{
              @"isChecked":@"ischecked",
              @"tagId":@"tagid",
              @"tagName":@"tagname",
              @"tagValue":@"tagvalue"
              }];
}
2、模型包含模型時(shí)的使用, 被包含的模型需要聲明protocol

eg:KSAlreadyBuyListModel 包含一個(gè)屬性KSAlreadyBuyModel, 我們需要將KSAlreadyBuyModel聲明protocol,不然會(huì)解析失敗。

@class StoryModel, AblumModel;

@protocol KSAlreadyBuyModel <NSObject>
@end

@interface KSAlreadyBuyModel : KSBaseModel

@property (nonatomic, strong) StoryModel *storyModel;
@property (nonatomic, strong) AblumModel *ablumModel;

@end

@protocol KSAlreadyBuyListModel <NSObject>
@end

@interface KSAlreadyBuyListModel : KSBaseModel

@property (nonatomic, copy) NSString *contentid;
@property (nonatomic, copy) NSString *contenttype;
@property (nonatomic, copy) NSString *iconurl;
@property (nonatomic, copy) NSString *orderno;
@property (nonatomic, copy) NSString *productid;
@property (nonatomic, copy) NSString *productname;
@property (nonatomic, copy) NSString *realityprice;
@property (nonatomic, strong) KSAlreadyBuyModel *param;

@end
3、如果你在同一個(gè).h中為了解析所有數(shù)據(jù),創(chuàng)建了多個(gè)model,一定要記得這些model在.m文件中實(shí)現(xiàn)他們。eg:上面的第二個(gè)。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容