JSONModel

Magical Data Modelling Framework for JSON

https://github.com/icanzilb/JSONModel

New: In version 0.12.0 I added experimental support for exportingJSON modelstoCoreData.

最新消息:在0.12.0版本中,我试验性的支持将 JSON models 转化成 CoreData .

Give it a try and let me know, post an issue or just get in touch. Try something like that:

如果你试验过了,有空告知哥一下,哥写开源库也不容易,发一篇博文或者给个链接以表支持:

NSError*error=nil;GitHubRepoEntity*entity=[GitHubRepoEntityentityWithModel:modelinContext:self.managedObjectContexterror:&error];[self.managedObjectContextsave:nil];

If you like JSONModel and use it can you please: 1) star this repo 2)send me some feedback. Thanks!

JSONModel is a library, which allows rapid creation of smart data models. You can use it in your iOS or OSX apps.

JSONModel automatically introspects your model classes and the structure of your JSON input and reduces drastically the amount of code you have to write.

如果你喜欢 JSONModel ,那么你可以:1)长期关注这个开源项目,2)你是土豪的话,给哥捐点吧,谢谢.

JSONModel 是一个库,他能智能并且快速的创建出数据 model,你可以在你的 iOS 项目或者 OSX 项目上使用它.

Adding JSONModel to your project

添加 JSONModel 到你的工程中

Requirements

需要的环境:

ARC only; iOS 5.0+ / OSX 10.7+

SystemConfiguration.framework

ARC,iOS 5.0+ / OSX 10.7 +

引入框架SystemConfiguration.framework

Get it as: 1) source files

Download the JSONModel repository as azip fileor clone it

Copy the JSONModel sub-folder into your Xcode project

Link your app to SystemConfiguration.framework

1.  下载 JSONModel zip包

2.  将 JSONModel 文件夹拷贝到你的工程项目中

3.  将库 SystemConfiguration.framework 添加上

or 2) via Cocoa pods

In your project'sPodfileadd the JSONModel pod:

使用 Cocoa pods 来安装:

pod'JSONModel'

If you want to read more about CocoaPods, have a look atthis short tutorial.

如果你不会用 CocoaPods,你可以看看这简单的教程。

Source code documentation

源码的文档

The source code includes class docs, which you can build yourself and import into Xcode:

源码本身包含了类的文档,你可以自己编译后导入到你的Xcode中:

If you don't already haveappledocinstalled, install it withhomebrewby typingbrew install appledoc.

Install the documentation into Xcode by typingappledoc .in the root directory of the repository.

Restart Xcode if it's already running.

1.  如果你还没安装 appledoc ,先安装 appledoc

2.  在Xcode上键入 appledoc 安装文档,在根目录下

3.  重启Xcode

Basic usage

基本使用

Consider you have a JSON like this:

假设你的 JSON 串像下面这样子:

{"id":"10","country":"Germany","dialCode":49,"isInEurope":true}

Create a new Objective-C class for your data model and make it inherit the JSONModel class.

Declare properties in your header file with the name of the JSON keys:

创建一个你自己的类,并继承至 JSONModel

在你的头文件里面进行声明你所需要的 JSON key值

#import "JSONModel.h"@interfaceCountryModel:JSONModel@property(assign,nonatomic)intid;@property(strong,nonatomic)NSString*country;@property(strong,nonatomic)NSString*dialCode;@property(assign,nonatomic)BOOLisInEurope;@end

There's no need to do anything in the.mfile.

.m文件中你不需要做其他的事情了.

Initialize your model with data:

初始化你的 model ,如下所示:

#import "CountryModel.h"...NSString*json=(fetchhereJSONfromInternet)...NSError*err=nil;CountryModel*country=[[CountryModelalloc]initWithString:jsonerror:&err];

If the validation of the JSON passes you have all the corresponding properties in your model populated from the JSON. JSONModel will also try to convert as much data to the types you expect, in the example above it will:

如果传过来的 JSON 合法,你所定义的所有的属性都会与该 JSON 值相匹配,并且 JSONModel 也会尝试尽可能的转换成你所想要的数据,就像上面的例子:

convert "id" from string (in the JSON) to an int for your class

just copy country's value

convert dialCode from number (in the JSON) to an NSString value

finally convert isInEurope to a BOOL for your BOOL property

转化 "id",从字符串转换成 int 型

拷贝 country 属性的值

转换 dialCode ,从NSNumber 转换为 NSString 值

最后一个呢是将 isInEurope 转换成 BOOL 的属性

And the good news is all you had to do is define the properties and their expected types.

所以,你需要做的就是定义出你期望的属性就行了。

Online tutorials

在线教程

Official website:http://www.jsonmodel.com

Class docs online:http://jsonmodel.com/docs/

Step-by-step tutorials:

傻瓜教程:

How to fetch and parse JSON by using data models

Performance optimisation for working with JSON feeds via JSONModel

How to make a YouTube app using MGBox and JSONModel

Examples

例子

Automatic name based mapping

命名自动匹配

{  "id": "123",  "name": "Product name",  "price": 12.95}

@interface ProductModel : JSONModel@property (assign, nonatomic) intid;@property (strong, nonatomic) NSString*name;@property (assign, nonatomic) floatprice;@end@implementation ProductModel@end

Model cascading (models including other models)

model中含有其他的model

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

@interface OrderModel : JSONModel@property (assign, nonatomic) intorder_id;@property (assign, nonatomic) floattotal_price;@property (strong, nonatomic)ProductModel*product;@end@implementation OrderModel@end

Model collections

model中含有其他model的集合

{  "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) intid;@property (strong, nonatomic) NSString*name;@property (assign, nonatomic) floatprice;@end@implementation ProductModel@end@interface OrderModel : JSONModel@property (assign, nonatomic) intorder_id;@property (assign, nonatomic) floattotal_price;@property (strong, nonatomic)NSArray*products;@end@implementation OrderModel@end

Key mapping

键值转回匹配

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

@interface OrderModel : JSONModel@property (assign, nonatomic) intid;@property (assign, nonatomic) floatprice;@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

Global key mapping (applies to all models in your app)

设置全局的键值转回匹配

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

Map automatically under_score case to camelCase

将下滑线转换成首字母大写

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

@interface OrderModel : JSONModel@property (assign, nonatomic) intorderId;@property (assign, nonatomic) floatorderPrice;@property (strong, nonatomic) NSString*orderProduct;@end@implementation OrderModel+(JSONKeyMapper*)keyMapper{  return[JSONKeyMappermapperFromUnderscoreCaseToCamelCase];}@end

Optional properties (i.e. can be missing or null)

可以为空的属性值

{

"id": "123",

"name": null,

"price": 12.95

}@interface ProductModel : JSONModel@property (assign, nonatomic) int id;@property (strong, nonatomic) NSString*name;@property (assign, nonatomic) float price;@property (strong, nonatomic) NSNumber*uuid;@end@implementation ProductModel@end

Ignored properties (i.e. JSONModel completely ignores them)

忽略某些属性

{

"id": "123",

"name": null

}@interface ProductModel : JSONModel@property (assign, nonatomic) int id;@property (strong, nonatomic) NSString*customProperty;@end@implementation ProductModel@end

Make all model properties optional (avoid if possible)

让所有的属性都可以有空的属性值

@implementation ProductModel+(BOOL)propertyIsOptional:(NSString*)propertyName

{

return YES;

}@end

Lazy convert collection items from dictionaries to models

将集合元素转换成 model

{  "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) intid;@property (strong, nonatomic) NSString*name;@property (assign, nonatomic) floatprice;@end@implementation ProductModel@end@interface OrderModel : JSONModel@property (assign, nonatomic) int order_id;@property (assign, nonatomic) float total_price;@property (strong, nonatomic) NSArrayConvertOnDemand>* products;@end@implementation OrderModel@end

Using the built-in thin HTTP client

使用内置的 HTTP 链接

//addextraheaders[[JSONHTTPClientrequestHeaders]setValue:@"MySecret"forKey:@"AuthorizationToken"];//makepost,getrequests[JSONHTTPClientpostJSONFromURLWithString:@"http://mydomain.com/api"params:@{@"postParam1":@"value1"}completion:^(idjson,JSONModelError*err){//checkerr,processjson...}];

Export model to NSDictionary or to JSON text

将 model 导出为字典或者json字符串

ProductModel*pm=[[ProductModelalloc]initWithString:jsonStringerror:nil];pm.name=@"Changed Name";//converttodictionaryNSDictionary*dict=[pmtoDictionary];//converttotextNSString*string=[pmtoJSONString];

json validation

data transformations

error handling

custom data validation

automatic compare and equality features

and more.

json数据键值匹配

数据转换

好的容错能力

自定义数据键值匹配

自动比较以及判断的特性

还有更多的等待亲来挖掘

以下是本人使用的测试结果

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,716评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,558评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,431评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,127评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,511评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,692评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,915评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,664评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,412评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,616评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,105评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,424评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,098评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,096评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,869评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,748评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,641评论 2 271

推荐阅读更多精彩内容