jsonmodel/jsonmodel


Magical Data Modeling Framework for JSON - allows rapid creation of smart data models. You can use it in your iOS, macOS, watchOS and tvOS apps.

License: MIT

Language: Objective-C


JSONModel - Magical Data Modeling Framework for JSON

JSONModel allows rapid creation of smart data models. You can use it in your iOS, macOS, watchOS and tvOS apps. Automatic introspection of your model classes and JSON input drastically reduces the amount of code you have to write.

See CHANGELOG.md for details on changes.

Installation

CocoaPods

pod 'JSONModel'

Carthage

github "jsonmodel/jsonmodel"

Manual

  1. download the JSONModel repository
  2. copy the JSONModel sub-folder into your Xcode project
  3. link your app to SystemConfiguration.framework

Basic Usage

Consider you have JSON like this:

{ "id": 10, "country": "Germany", "dialCode": 49, "isInEurope": true }
  • create a JSONModel subclass for your data model
  • declare properties in your header file with the name of the JSON keys:
@interface CountryModel : JSONModel
@property (nonatomic) NSInteger id;
@property (nonatomic) NSString *country;
@property (nonatomic) NSString *dialCode;
@property (nonatomic) BOOL isInEurope;
@end

There's no need to do anything in the implementation (.m) file.

  • initialize your model with data:
NSError *error;
CountryModel *country = [[CountryModel alloc] initWithString:myJson error:&error];

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:

  • convert id from string (in the JSON) to an int for your class
  • copy the country value
  • convert dialCode from a number (in the JSON) to an NSString value
  • copy the isInEurope value

All you have to do is define the properties and their expected types.

Examples

Automatic name based mapping

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

Model cascading (models including other models)

{
	"orderId": 104,
	"totalPrice": 13.45,
	"product": {
		"id": 123,
		"name": "Product name",
		"price": 12.95
	}
}
@interface ProductModel : JSONModel
@property (nonatomic) NSInteger id;
@property (nonatomic) NSString *name;
@property (nonatomic) float price;
@end

@interface OrderModel : JSONModel
@property (nonatomic) NSInteger orderId;
@property (nonatomic) float totalPrice;
@property (nonatomic) ProductModel *product;
@end

Model collections

{
	"orderId": 104,
	"totalPrice": 103.45,
	"products": [
		{
			"id": 123,
			"name": "Product #1",
			"price": 12.95
		},
		{
			"id": 137,
			"name": "Product #2",
			"price": 82.95
		}
	]
}
@protocol ProductModel;

@interface ProductModel : JSONModel
@property (nonatomic) NSInteger id;
@property (nonatomic) NSString *name;
@property (nonatomic) float price;
@end

@interface OrderModel : JSONModel
@property (nonatomic) NSInteger orderId;
@property (nonatomic) float totalPrice;
@property (nonatomic) NSArray <ProductModel> *products;
@end

Note: the angle brackets after NSArray contain a protocol. This is not the same as the Objective-C generics system. They are not mutually exclusive, but for JSONModel to work, the protocol must be in place.

Also property can have generics info for compiler

@interface OrderModel : JSONModel
@property (nonatomic) NSInteger orderId;
@property (nonatomic) float totalPrice;
@property (nonatomic) NSArray<ProductModel *> <ProductModel> *products;
@end

Nested key mapping

{
	"orderId": 104,
	"orderDetails": {
		"name": "Product #1",
		"price": {
			"usd": 12.95
		}
	}
}
@interface OrderModel : JSONModel
@property (nonatomic) NSInteger id;
@property (nonatomic) NSString *productName;
@property (nonatomic) float price;
@end

@implementation OrderModel

+ (JSONKeyMapper *)keyMapper
{
	return [[JSONKeyMapper alloc] initWithModelToJSONDictionary:@{
		@"id": @"orderId",
		@"productName": @"orderDetails.name",
		@"price": @"orderDetails.price.usd"
	}];
}

@end

Map automatically to snake_case

{
	"order_id": 104,
	"order_product": "Product #1",
	"order_price": 12.95
}
@interface OrderModel : JSONModel
@property (nonatomic) NSInteger orderId;
@property (nonatomic) NSString *orderProduct;
@property (nonatomic) float orderPrice;
@end

@implementation OrderModel

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

@end

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

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

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

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

Making scalar types optional

{
	"id": null
}
@interface ProductModel : JSONModel
@property (nonatomic) NSInteger id;
@end

@implementation ProductModel

+ (BOOL)propertyIsOptional:(NSString *)propertyName
{
	if ([propertyName isEqualToString:@"id"])
		return YES;

	return NO;
}

@end

Export model to NSDictionary or JSON

ProductModel *pm = [ProductModel new];
pm.name = @"Some Name";

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

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

Custom data transformers

@interface JSONValueTransformer (CustomTransformer)
@end

@implementation JSONValueTransformer (CustomTransformer)

- (NSDate *)NSDateFromNSString:(NSString *)string
{
	NSDateFormatter *formatter = [NSDateFormatter new];
	formatter.dateFormat = APIDateFormat;
	return [formatter dateFromString:string];
}

- (NSString *)JSONObjectFromNSDate:(NSDate *)date
{
	NSDateFormatter *formatter = [NSDateFormatter new];
	formatter.dateFormat = APIDateFormat;
	return [formatter stringFromDate:date];
}

@end

Custom getters/setters

@interface ProductModel : JSONModel
@property (nonatomic) NSInteger id;
@property (nonatomic) NSString *name;
@property (nonatomic) float price;
@property (nonatomic) NSLocale *locale;
@end

@implementation ProductModel

- (void)setLocaleWithNSString:(NSString *)string
{
	self.locale = [NSLocale localeWithLocaleIdentifier:string];
}

- (void)setLocaleWithNSDictionary:(NSDictionary *)dictionary
{
	self.locale = [NSLocale localeWithLocaleIdentifier:dictionary[@"identifier"]];
}

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

@end

Custom JSON validation

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

@implementation ProductModel

- (BOOL)validate:(NSError **)error
{
	if (![super validate:error])
		return NO;

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

	return YES;
}

@end

License

MIT licensed - see LICENSE file.

Contributing

We love pull requests! See CONTRIBUTING.md for full details.

Project Statistics

Sourcerank 12
Repository Size 1.56 MB
Stars 6,634
Forks 1,076
Watchers 278
Open issues 17
Dependencies 1
Contributors 63
Tags 30
Created
Last updated
Last pushed

Top Contributors See all

Marin Todorov James Billingham Jay Abbott Dustin Bachrach BB9z Quanlong Robin Zhang brian-intuit Mark Joslin Robin Zhang Marcus Rohrmoser Johnykutty Mathew Stefan Kendall Julien Vignali Michael Rico Becker shuo Mark Aufflick Bram Huenaerts Stefan-Hintz

Packages Referencing this Repo

jsonmodel/jsonmodel
Magical Data Modeling Framework for JSON - allows rapid creation of smart data models. You can us...
Latest release 1.8.0 - Published - 6.63K stars
JSONModel
Magical Data Modelling Framework for JSON. Create rapidly powerful, atomic and smart data model c...
Latest release 1.8.0 - Updated - 6.63K stars

Recent Tags See all

1.8.0 September 19, 2018
1.7.0 October 07, 2016
v1.6.0 October 05, 2016
1.6.0 October 05, 2016
1.5.1 September 12, 2016
1.5.0 September 12, 2016
1.4.2 September 11, 2016
1.4.1 September 11, 2016
1.4.0 August 18, 2016
1.3.0 July 22, 2016
1.2.0 December 30, 2015
1.1.2 October 19, 2015
1.1.0 May 10, 2015
1.0.2 January 21, 2015
1.0.1 August 11, 2014

Interesting Forks See all

ben46/JSONModel
better than coredata!
Objective-C - MIT - Last pushed - 22 stars - 5 forks
thehtb/JSONModel
The High Technology Bureau's FORK of JSONModel
Objective-C - MIT - Last pushed - 9 stars - 1 forks
ZeusFramework/JSONModel
Magical Data Modelling Framework for JSON. Create rapidly powerful, atomic and smart data model c...
Objective-C - MIT - Updated - 1 stars
MacPass/jsonmodel
Magical Data Modeling Framework for JSON - allows rapid creation of smart data models. You can us...
Objective-C - Updated - 1 stars
CNXTEoE/jsonmodel
Magical Data Modeling Framework for JSON - allows rapid creation of smart data models. You can us...
Objective-C - Published - 1 stars

Something wrong with this page? Make a suggestion

Last synced: 2018-10-22 23:41:58 UTC

Login to resync this repository