jsonModel使用

流弊的JSON數據模型框架

https://github.com/jsonmodel/jsonmodeljavascript

版本 1.3.0


若是你喜歡JSONModel,而且使用了它,請你:java

  • star一下git

  • 給我一些反饋. 多謝!github


 
JSONModel for iOS and OSX

JSONModel 是一個可以快速巧妙的建立數據模型的庫. 你能夠在 iOS or OSX APP中使用它.json

JSONModel 自動檢查JOSN模型和結構體, 完全的減小你的代碼量.api

 
 

添加JSONModel到你的項目中

要求

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

as: 1) 源文件

1.下載JSONModel.zip文件
2.將它拷貝到你的項目中
3.導入SystemConfiguration.framework框架ruby

or 2)使用 CocoaPods

pod 'JSONModel' 

若是你想關於CocoaPods瞭解更多,請參考這個簡單的教程.bash

or 3) 使用 Carthage

在你的項目的Cartfile添加JSONModel:app

github "jsonmodel/jsonmodel" 

文檔

你能夠查看在線閱讀文檔: http://cocoadocs.org/docsets/JSONModel框架


基本使用

涉想你的JSON數據像這樣:

{ "id": "10", "country": "Germany", "dialCode": 49, "isInEurope": true } 
  • 爲你的數據模型建立一個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文件中不須要作任何事情.

  • 用數據初始化你的model:
#import "CountryModel.h" ... NSString* json = (fetch here JSON from Internet) ... NSError* err = nil; CountryModel* country = [[CountryModel alloc] initWithString:json error:&err]; 

若是傳過來的JSON合法,你所定義的全部的屬性都會與該JSON的值想對應,甚至JSONModel會嘗試去轉換數據爲你指望的類型,如上所示:

  • 轉換id,從字符串轉換爲int
  • 只須要拷貝一下country的值
  • 轉換diaCode,從number轉換爲字符串
  • 最後一個是將isInEurope轉換爲BOOL屬性

因此,你所須要作的就是將你的屬性定義爲指望的類型.


在線教程

官方網站: http://www.jsonmodel.com

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

傻瓜教程:


舉個栗子

命名自動匹配

{
  "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 

注意: 尖括號後 <code>NSArray</code> 包含一個協議. 這跟Objective-C原生的泛型不是一個概念. 他們不會衝突, 但對於JSONModel來講,協議必須在一個地方聲明.

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 

設置全局鍵映射(應用於全部model)

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

設置下劃線自動轉駝峯

{
  "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 

可選屬性 (就是說這個屬性能夠爲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 

忽略屬性 (就是徹底忽略這個屬性)

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

設置全部的屬性爲可選(全部屬性值能夠爲空)

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

使用JSONModel自帶的 HTTP 請求

//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轉化爲字典或者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]; 

自定義數據的轉換

@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校驗

@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 
  • 錯誤處理
  • 自定義數據校驗
  • 自動比較和相等判斷
  • 更多.
相關文章
相關標籤/搜索