使用 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 = [GitHubRepoEntity entityWithModel:model
                                                   inContext:self.managedObjectContext
                                                       error:&error];
[self.managedObjectContext save: 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

  1. Download the JSONModel repository as azip fileor clone it
  2. Copy the JSONModel sub-folder into your Xcode project
  3. 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中:

  1. If you don't already haveappledocinstalled,install it withhomebrewby typingbrew install appledoc.
  2. Install the documentation into Xcode by typingappledoc .in the root directory of the repository.
  3. 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"

@interface CountryModel : JSONModel

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

@end

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

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

  • Initialize your model with data:
  • 初始化你的 model,如下所示:
#import "CountryModel.h"
...

NSString* json = (fetch here JSON from Internet) ... 
NSError* err = nil;
CountryModel* country = [[CountryModel alloc] initWithString:json error:&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:

傻瓜教程:


Examples

例子

Automatic name based mapping

命名自动匹配

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

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) int order_id;
@property (assign,nonatomic) float total_price;
@property (strong,nonatomic) ProductModel* product;
@end

@implementation OrderModel
@end

Model collections

model中含有其他model的集合

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) float price;
@end

@implementation ProductModel
@end

@interface OrderModel : JSONModel
@property (assign,nonatomic) NSArray<ProductModel>* products;
@end

@implementation OrderModel
@end

Key mapping

键值转回匹配

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

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_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

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<Optional>* name;
@property (assign,nonatomic) float price;
@property (strong,nonatomic) NSNumber<Optional>* uuid;
@end

@implementation ProductModel
@end

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

忽略某些属性

@interface ProductModel : JSONModel
@property (assign,nonatomic) NSString<Ignore>* 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",{
      "id": "137","name": "Product #2","price": 82.95
    }
  ]
}
@protocol ProductModel
@end

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

@implementation OrderModel
@end

Using the built-in thin HTTP client

使用内置的 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 ...

                               }];

Export model to NSDictionary or to JSON text

将 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];

  • json validation
  • data transformations
  • error handling
  • custom data validation
  • automatic compare and equality features
  • and more.
  • json数据键值匹配
  • 数据转换
  • 好的容错能力
  • 自定义数据键值匹配
  • 自动比较以及判断的特性
  • 还有更多的等待亲来挖掘

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


文章浏览阅读2.4k次。最近要优化cesium里的热力图效果,浏览了网络上的各种方法,发现大多是贴在影像上的。这么做好是好,但是会被自生添加的模型或者其他数据给遮盖。其次是网上的方法大多数是截取成一个矩形。不能自定义的截取自己所需要的。经过尝试,决定修改下cesium heatmap,让他达到我们需要的要求。首先先下载 cesium heatmap包。其中我们可以看到也是通过叠加entity达到添加canvas的方法绘制到地图上。我们先把这一段代码注释} else {} };
文章浏览阅读1.2w次,点赞3次,收藏19次。在 Python中读取 json文件也可以使用 sort ()函数,在这里我介绍一个简单的示例程序: (4)如果我们想将字符串转换为列表形式,只需要添加一个变量来存储需要转换的字符串即可。在上面的代码中,我们创建了一个名为` read`的对象,然后在文件的开头使用`./`关键字来命名该对象,并在文件中定义了一个名为` json`的变量,并在其中定义了一个名为` json`的字段。比如,我们可以使用 read方法读取 json文件中的内容,然后使用 send方法将其发送到 json文件中。_python怎么读取json文件
文章浏览阅读1.4k次。首字母缩略词 API 代表应用程序编程接口,它是一种设备,例如用于使用编程代码发送和检索数据的服务器。最常见的是,该技术用于从源检索数据并将其显示给软件应用程序及其用户。当您访问网页时,API 的工作方式与浏览器相同,信息请求会发送到服务器,如何在 Windows PC 中手动创建系统还原点服务器会做出响应。唯一的区别是服务器响应的数据类型,对于 API,数据是 JSON 类型。JSON 代表 JavaScript Object Notation,它是大多数软件语言中 API 的标准数据表示法。_api是什么 python
文章浏览阅读802次,点赞10次,收藏10次。解决一个JSON反序列化问题-空字符串变为空集合_cannot coerce empty string ("") to element of `java.util.arraylist
文章浏览阅读882次。Unity Json和Xml的序列化和反序列化_unity json反序列化存储换行
文章浏览阅读796次。reader.readAsText(data.file)中data.file的数据格式为。使用FileReader对象读取文件内容,最后将文件内容进行处理使用。_a-upload 同时支持文件和文件夹
文章浏览阅读775次,点赞19次,收藏10次。fastjson是由国内的阿里推出的一种json处理器,由java语言编写,无依赖,不需要引用额外的jar包,能直接运行在jdk环境中,它的解析速度是非常之快的,目前超过了所有json库。提示:以下是引用fastjson的方法,数据未涉及到私密信息。_解析器用fastjson还是jackson
文章浏览阅读940次。【Qt之JSON文件】QJsonDocument、QJsonObject、QJsonArray等类介绍及使用_使用什么方法检查qjsondocument是否为空
文章浏览阅读957次,点赞34次,收藏22次。主要内容原生 ajax重点重点JSON熟悉章节目标掌握原生 ajax掌握jQuery ajax掌握JSON第一节 ajax1. 什么是ajaxAJAX 全称为,表示异步的Java脚本和Xml文件,是一种异步刷新技术。2. 为什么要使用ajaxServlet进行网页的变更往往是通过请求转发或者是重定向来完成,这样的操作更新的是整个网页,如果我们只需要更新网页的局部内容,就需要使用到AJAX来处理了。因为只是更新局部内容,因此,Servlet。
文章浏览阅读1.4k次,点赞45次,收藏13次。主要介绍了JsonFormat与@DateTimeFormat注解实例解析,文中通过示例代码介绍的非常详细,对大家的学习 或者工作具有一定的参考学习价值,需要的朋友可以参考下 这篇文章主要介绍了从数据库获取时间传到前端进行展示的时候,我们有时候可能无法得到一个满意的时间格式的时间日期,在数据库中显 示的是正确的时间格式,获取出来却变成了时间戳,@JsonFormat注解很好的解决了这个问题,我们通过使用 @JsonFormat可以很好的解决:后台到前台时间格式保持一致的问题,
文章浏览阅读1k次。JsonDeserialize:json反序列化注解,作用于setter()方法,将json数据反序列化为java对象。可以理解为用在处理接收的数据上。_jsondeserialize
文章浏览阅读2.7k次。labelme标注的json文件是在数据标注时产生,不能直接应用于模型训练。各大目标检测训练平台或项目框架均有自己的数据格式要求,通常为voc、coco或yolo格式。由于yolov8项目比较火热,故此本博文详细介绍将json格式标注转化为yolo格式的过程及其代码。_labelme json 转 yolo
文章浏览阅读790次,点赞26次,收藏6次。GROUP_CONCAT_UNORDERED(): 与GROUP_CONCAT类似,但不保证结果的顺序。COUNT_DISTINCT_AND_ORDERED(): 计算指定列的不同值的数量,并保持结果的顺序。COUNT_ALL_DISTINCT(): 计算指定列的所有不同值的数量(包括NULL)。AVG_RANGE(): 计算指定列的最大值和最小值之间的差异的平均值。JSON_OBJECT(): 将结果集中的行转换为JSON对象。COUNT_DISTINCT(): 计算指定列的不同值的数量。_mysql json 聚合
文章浏览阅读1.2k次。ajax同步与异步,json-serve的安装与使用,node.js的下载_json-serve 与node版本
文章浏览阅读1.7k次。`.net core`提供了Json处理模块,在命名空间`System.Text.Json`中,下面通过顶级语句,对C#的Json功能进行讲解。_c# json
文章浏览阅读2.8k次。主要介绍了python对于json文件的读写操作内容_python读取json文件
文章浏览阅读770次。然而,有时候在处理包含中文字符的Json数据时会出现乱码的情况。本文将介绍一种解决Json中文乱码问题的常见方法,并提供相应的源代码和描述。而某些情况下,中文字符可能会被错误地编码或解码,导致乱码的出现。通过适当地控制编码和解码过程,我们可以有效地处理包含中文字符的Json数据,避免乱码的发生。通过控制编码和解码过程,我们可以确保Json数据中的中文字符能够正确地传输和解析。为了解决这个问题,我们可以使用C#的System.Text.Encoding类提供的方法进行编码和解码的控制。_c# json 中文编码
文章浏览阅读997次。【代码】【工具】XML和JSON互相转换。_xml 转json
文章浏览阅读1.1k次。json path 提取数据_jsonpath数组取值
文章浏览阅读3w次,点赞35次,收藏36次。本文主要介绍了pandas read_json时ValueError: Expected object or value的解决方案,希望能对学习python的同学们有所帮助。文章目录1. 问题描述2. 解决方案_valueerror: expected object or value