README.md 12 KB
Newer Older
1
## Magical Data Modelling Framework for JSON
曹云霄's avatar
曹云霄 committed
2

3
### Version 1.2.0
曹云霄's avatar
曹云霄 committed
4

5
#####NB: Swift works in a different way under the hood than Objective-C. Therefore I can't find a way to re-create JSONModel in Swift. JSONModel in Objective-C works in Swift apps through CocoaPods or as an imported Objective-C library.
曹云霄's avatar
曹云霄 committed
6

7 8
---
If you like JSONModel and use it, could you please:
曹云霄's avatar
曹云霄 committed
9

10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
 * star this repo

 * send me some feedback. Thanks!

---

![JSONModel for iOS and OSX](http://jsonmodel.com/img/jsonmodel_logolike.png)

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.

[![](http://www.touch-code-magazine.com/img/json.png)](http://www.touch-code-magazine.com/img/json.png)


------------------------------------
Adding JSONModel to your project
====================================

#### Requirements

* ARC only; iOS 5.0+ / OSX 10.7+
* **SystemConfiguration.framework**

#### Get it as: 1) source files

1. Download the JSONModel repository as a [zip file](https://github.com/icanzilb/JSONModel/archive/master.zip) or clone it
2. Copy the JSONModel sub-folder into your Xcode project
3. Link your app to SystemConfiguration.framework

#### or 2) via Cocoa pods

In your project's **Podfile** add the JSONModel pod:
曹云霄's avatar
曹云霄 committed
43 44 45 46

```ruby
pod 'JSONModel'
```
47 48 49
If you want to read more about CocoaPods, have a look at [this short tutorial](http://www.raywenderlich.com/12139/introduction-to-cocoapods).

#### or 3) via Carthage
曹云霄's avatar
曹云霄 committed
50

51
In your project's **Cartfile** add the JSONModel:
曹云霄's avatar
曹云霄 committed
52 53

```ruby
54
github "icanzilb/JSONModel"
曹云霄's avatar
曹云霄 committed
55 56
```

57 58
#### Source code documentation
The source code includes class docs, which you can build yourself and import into Xcode:
曹云霄's avatar
曹云霄 committed
59

60 61 62
1. If you don't already have [appledoc](http://gentlebytes.com/appledoc/) installed, install it with [homebrew](http://brew.sh/) by typing `brew install appledoc`.
2. Install the documentation into Xcode by typing `appledoc .` in the root directory of the repository.
3. Restart Xcode if it's already running.
曹云霄's avatar
曹云霄 committed
63

64 65 66
------------------------------------
Basic usage
====================================
曹云霄's avatar
曹云霄 committed
67

68 69 70
Consider you have a JSON like this:
```javascript
{"id":"10", "country":"Germany", "dialCode": 49, "isInEurope":true}
71
```
曹云霄's avatar
曹云霄 committed
72

73 74 75 76 77
 * 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:

```objective-c
#import "JSONModel.h"
曹云霄's avatar
曹云霄 committed
78 79

@interface CountryModel : JSONModel
80 81 82 83 84 85

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

曹云霄's avatar
曹云霄 committed
86 87
@end
```
88
There's no need to do anything in the **.m** file.
曹云霄's avatar
曹云霄 committed
89

90
 * Initialize your model with data:
曹云霄's avatar
曹云霄 committed
91

92 93 94 95 96 97 98
```objective-c
#import "CountryModel.h"
...

NSString* json = (fetch here JSON from Internet) ...
NSError* err = nil;
CountryModel* country = [[CountryModel alloc] initWithString:json error:&err];
曹云霄's avatar
曹云霄 committed
99 100 101

```

102
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:
曹云霄's avatar
曹云霄 committed
103

104 105 106 107
* 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
曹云霄's avatar
曹云霄 committed
108

109
And the good news is all you had to do is define the properties and their expected types.
曹云霄's avatar
曹云霄 committed
110

111 112
-------
#### Online tutorials
曹云霄's avatar
曹云霄 committed
113 114


115
Official website: [http://www.jsonmodel.com](http://www.jsonmodel.com)
曹云霄's avatar
曹云霄 committed
116

117 118 119 120 121 122 123
Class docs online: [http://jsonmodel.com/docs/](http://jsonmodel.com/docs/)

Step-by-step tutorials:

 * [How to fetch and parse JSON by using data models](http://www.touch-code-magazine.com/how-to-fetch-and-parse-json-by-using-data-models/)

 * [Performance optimisation for working with JSON feeds via JSONModel](http://www.touch-code-magazine.com/performance-optimisation-for-working-with-json-feeds-via-jsonmodel/)
曹云霄's avatar
曹云霄 committed
124

125
 * [How to make a YouTube app using MGBox and JSONModel](http://www.touch-code-magazine.com/how-to-make-a-youtube-app-using-mgbox-and-jsonmodel/)
曹云霄's avatar
曹云霄 committed
126

127 128 129 130 131 132 133 134 135
-------
Examples
=======

#### Automatic name based mapping
<table>
<tr>
<td valign="top">
<pre>
曹云霄's avatar
曹云霄 committed
136
{
137 138 139
  "id": "123",
  "name": "Product name",
  "price": 12.95
曹云霄's avatar
曹云霄 committed
140
}
141 142 143 144
</pre>
</td>
<td>
<pre>
曹云霄's avatar
曹云霄 committed
145
@interface ProductModel : JSONModel
146 147 148
@property (assign, nonatomic) int id;
@property (strong, nonatomic) NSString* name;
@property (assign, nonatomic) float price;
曹云霄's avatar
曹云霄 committed
149 150
@end

151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
@implementation ProductModel
@end
</pre>
</td>
</tr>
</table>

#### Model cascading (models including other models)
<table>
<tr>
<td valign="top">
<pre>
{
  "order_id": 104,
  "total_price": 13.45,
  "product" : {
    "id": "123",
    "name": "Product name",
    "price": 12.95
  }
}
</pre>
</td>
<td valign="top">
<pre>
曹云霄's avatar
曹云霄 committed
176
@interface OrderModel : JSONModel
177 178 179
@property (assign, nonatomic) int order_id;
@property (assign, nonatomic) float total_price;
@property (strong, nonatomic) <b>ProductModel*</b> product;
曹云霄's avatar
曹云霄 committed
180 181
@end

182 183 184 185 186 187 188 189 190 191 192 193
@implementation OrderModel
@end
</pre>
</td>
</tr>
</table>

#### Model collections
<table>
<tr>
<td valign="top">
<pre>
曹云霄's avatar
曹云霄 committed
194
{
195 196 197 198 199 200 201 202 203 204 205 206 207 208
  "order_id": 104,
  "total_price": 103.45,
  "products" : [
    {
      "id": "123",
      "name": "Product #1",
      "price": 12.95
    },
    {
      "id": "137",
      "name": "Product #2",
      "price": 82.95
    }
  ]
曹云霄's avatar
曹云霄 committed
209
}
210 211 212 213 214 215
</pre>
</td>
<td valign="top">
<pre>
<b>@protocol ProductModel
@end</b>
曹云霄's avatar
曹云霄 committed
216

217
@interface ProductModel : JSONModel
218 219 220
@property (assign, nonatomic) int id;
@property (strong, nonatomic) NSString* name;
@property (assign, nonatomic) float price;
曹云霄's avatar
曹云霄 committed
221 222
@end

223
@implementation ProductModel
曹云霄's avatar
曹云霄 committed
224
@end
225

226 227 228 229 230
@interface OrderModel : JSONModel
@property (assign, nonatomic) int order_id;
@property (assign, nonatomic) float total_price;
@property (strong, nonatomic) <b>NSArray&lt;ProductModel&gt;*</b> products;
@end
231

232 233 234 235 236 237 238 239 240 241 242 243
@implementation OrderModel
@end
</pre>
</td>
</tr>
</table>

#### Key mapping
<table>
<tr>
<td valign="top">
<pre>
曹云霄's avatar
曹云霄 committed
244
{
245 246 247 248 249 250 251 252 253
  "order_id": 104,
  "order_details" : [
    {
      "name": "Product#1",
      "price": {
        "usd": 12.95
      }
    }
  ]
曹云霄's avatar
曹云霄 committed
254
}
255 256 257 258
</pre>
</td>
<td valign="top">
<pre>
曹云霄's avatar
曹云霄 committed
259
@interface OrderModel : JSONModel
260 261 262
@property (assign, nonatomic) int id;
@property (assign, nonatomic) float price;
@property (strong, nonatomic) NSString* productName;
曹云霄's avatar
曹云霄 committed
263 264 265 266
@end

@implementation OrderModel

267
+(JSONKeyMapper*)keyMapper
曹云霄's avatar
曹云霄 committed
268
{
269 270 271 272 273
  return [[JSONKeyMapper alloc] initWithDictionary:@{
  <b>  @"order_id": @"id",
    @"order_details.name": @"productName",
    @"order_details.price.usd": @"price"</b>
  }];
曹云霄's avatar
曹云霄 committed
274 275 276
}

@end
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
</pre>
</td>
</tr>
</table>

#### Global key mapping (applies to all models in your app)
<table>
<tr>
<td valign="top">
<pre>
<b>[JSONModel setGlobalKeyMapper:[</b>
    [JSONKeyMapper alloc] initWithDictionary:@{
      @"item_id":@"ID",
      @"item.name": @"itemName"
   }]
<b>];</b>

</pre>
</td>
</tr>
</table>

#### Map automatically under_score case to camelCase
<table>
<tr>
<td valign="top">
<pre>
曹云霄's avatar
曹云霄 committed
304
{
305 306 307
  "order_id": 104,
  "order_product" : @"Product#1",
  "order_price" : 12.95
曹云霄's avatar
曹云霄 committed
308
}
309 310 311 312
</pre>
</td>
<td valign="top">
<pre>
313
@interface OrderModel : JSONModel
314 315 316 317 318

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

曹云霄's avatar
曹云霄 committed
319 320 321 322
@end

@implementation OrderModel

323
+(JSONKeyMapper*)keyMapper
曹云霄's avatar
曹云霄 committed
324
{
325
  return <b>[JSONKeyMapper mapperFromUnderscoreCaseToCamelCase];</b>
曹云霄's avatar
曹云霄 committed
326 327 328
}

@end
329 330 331 332 333 334 335 336 337 338
</pre>
</td>
</tr>
</table>

#### Optional properties (i.e. can be missing or null)
<table>
<tr>
<td valign="top">
<pre>
曹云霄's avatar
曹云霄 committed
339
{
340 341 342
  "id": "123",
  "name": null,
  "price": 12.95
曹云霄's avatar
曹云霄 committed
343
}
344 345 346 347
</pre>
</td>
<td>
<pre>
348
@interface ProductModel : JSONModel
349 350 351 352
@property (assign, nonatomic) int id;
@property (strong, nonatomic) NSString<b>&lt;Optional&gt;</b>* name;
@property (assign, nonatomic) float price;
@property (strong, nonatomic) NSNumber<b>&lt;Optional&gt;</b>* uuid;
曹云霄's avatar
曹云霄 committed
353 354
@end

355 356 357 358 359 360 361 362 363 364 365 366
@implementation ProductModel
@end
</pre>
</td>
</tr>
</table>

#### Ignored properties (i.e. JSONModel completely ignores them)
<table>
<tr>
<td valign="top">
<pre>
曹云霄's avatar
曹云霄 committed
367
{
368 369
  "id": "123",
  "name": null
370
}
371 372 373 374
</pre>
</td>
<td>
<pre>
375
@interface ProductModel : JSONModel
376 377
@property (assign, nonatomic) int id;
@property (strong, nonatomic) NSString<b>&lt;Ignore&gt;</b>* customProperty;
曹云霄's avatar
曹云霄 committed
378 379
@end

380 381 382 383 384 385
@implementation ProductModel
@end
</pre>
</td>
</tr>
</table>
曹云霄's avatar
曹云霄 committed
386

387 388 389 390 391 392 393 394

#### Make all model properties optional (avoid if possible)
<table>
<tr>
<td valign="top">
<pre>
@implementation ProductModel
<b>+(BOOL)propertyIsOptional:(NSString*)propertyName
曹云霄's avatar
曹云霄 committed
395
{
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
  return YES;
}</b>
@end
</pre>
</td>
</tr>
</table>


#### Lazy convert collection items from dictionaries to models
<table>
<tr>
<td valign="top">
<pre>
{
  "order_id": 104,
  "total_price": 103.45,
  "products" : [
    {
      "id": "123",
      "name": "Product #1",
      "price": 12.95
    },
    {
      "id": "137",
      "name": "Product #2",
      "price": 82.95
    }
  ]
曹云霄's avatar
曹云霄 committed
425
}
426 427 428 429 430 431
</pre>
</td>
<td valign="top">
<pre>
@protocol ProductModel
@end
曹云霄's avatar
曹云霄 committed
432 433

@interface ProductModel : JSONModel
434 435 436
@property (assign, nonatomic) int id;
@property (strong, nonatomic) NSString* name;
@property (assign, nonatomic) float price;
曹云霄's avatar
曹云霄 committed
437 438 439
@end

@implementation ProductModel
440
@end
曹云霄's avatar
曹云霄 committed
441

442 443 444 445 446
@interface OrderModel : JSONModel
@property (assign, nonatomic) int order_id;
@property (assign, nonatomic) float total_price;
@property (strong, nonatomic) NSArray&lt;ProductModel, <b>ConvertOnDemand</b>&gt;* products;
@end
曹云霄's avatar
曹云霄 committed
447

448
@implementation OrderModel
449
@end
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
</pre>
</td>
</tr>
</table>

#### Using the built-in thin HTTP client

```objective-c

//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 ...

                               }];
曹云霄's avatar
曹云霄 committed
470 471
```

472 473 474
#### Export model to NSDictionary or to JSON text

```objective-c
曹云霄's avatar
曹云霄 committed
475

476 477
ProductModel* pm = [[ProductModel alloc] initWithString:jsonString error:nil];
pm.name = @"Changed Name";
曹云霄's avatar
曹云霄 committed
478

479 480 481 482 483
//convert to dictionary
NSDictionary* dict = [pm toDictionary];

//convert to text
NSString* string = [pm toJSONString];
曹云霄's avatar
曹云霄 committed
484 485 486

```

487
#### Custom data transformers
曹云霄's avatar
曹云霄 committed
488

489
```objective-c
曹云霄's avatar
曹云霄 committed
490 491 492

@implementation JSONValueTransformer (CustomTransformer)

493 494 495 496
- (NSDate *)NSDateFromNSString:(NSString*)string {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:APIDateFormat];
    return [formatter dateFromString:string];
曹云霄's avatar
曹云霄 committed
497 498
}

499 500 501 502
- (NSString *)JSONObjectFromNSDate:(NSDate *)date {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:APIDateFormat];
    return [formatter stringFromDate:date];
曹云霄's avatar
曹云霄 committed
503 504 505
}

@end
506

曹云霄's avatar
曹云霄 committed
507 508
```

509 510 511
#### Custom handling for specific properties

```objective-c
曹云霄's avatar
曹云霄 committed
512 513

@interface ProductModel : JSONModel
514 515 516 517
@property (assign, nonatomic) int id;
@property (strong, nonatomic) NSString* name;
@property (assign, nonatomic) float price;
@property (strong, nonatomic) NSLocale *locale;
曹云霄's avatar
曹云霄 committed
518 519 520 521
@end

@implementation ProductModel

522 523 524
// Convert and assign the locale property
- (void)setLocaleWithNSString:(NSString*)string {
    self.locale = [NSLocale localeWithLocaleIdentifier:string];
曹云霄's avatar
曹云霄 committed
525 526
}

527 528
- (NSString *)JSONObjectForLocale {
    return self.locale.localeIdentifier;
529
}
曹云霄's avatar
曹云霄 committed
530

531 532
@end

533
```
534

535 536 537 538 539
* json validation
* error handling
* custom data validation
* automatic compare and equality features
* and more.
曹云霄's avatar
曹云霄 committed
540

541
-------
曹云霄's avatar
曹云霄 committed
542

543 544
Misc
=======
曹云霄's avatar
曹云霄 committed
545

546
Author: [Marin Todorov](http://www.touch-code-magazine.com)
曹云霄's avatar
曹云霄 committed
547

548 549
Contributors: Christian Hoffmann, Mark Joslin, Julien Vignali, Symvaro GmbH, BB9z.
Also everyone who did successful [pull requests](https://github.com/icanzilb/JSONModel/graphs/contributors).
曹云霄's avatar
曹云霄 committed
550

551
Change log : [https://github.com/icanzilb/JSONModel/blob/master/Changelog.md](https://github.com/icanzilb/JSONModel/blob/master/Changelog.md)
曹云霄's avatar
曹云霄 committed
552

553 554 555
-------
#### License
This code is distributed under the terms and conditions of the MIT license.
曹云霄's avatar
曹云霄 committed
556

557 558
-------
#### Contribution guidelines
曹云霄's avatar
曹云霄 committed
559

560
**NB!** If you are fixing a bug you discovered, please add also a unit test so I know how exactly to reproduce the bug before merging.
曹云霄's avatar
曹云霄 committed
561