Giter Club home page Giter Club logo

jsonmodel's Introduction

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.

jsonmodel's People

Contributors

ajanauskas avatar amitpdev avatar andrewagain avatar aufflick avatar billinghamj avatar brian-intuit avatar ccbb avatar cybertk avatar dbachrach avatar ddebin avatar edelabar avatar fictorial avatar heistings avatar icanzilb avatar j-h-a avatar jiyee avatar jkmathew avatar joslinm avatar mro avatar nashfive avatar nsmutablestring avatar ricobeck avatar robinzhangx avatar shuoli84 avatar stefan-hintz avatar stefankendall2 avatar thirakornp avatar vibrazy avatar xdream86 avatar zaidos avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jsonmodel's Issues

Problem with raywenderlich tutorial

Hello, i'm sorry if i write you here, but i doesn't know where i can contact you :) i have follow this amazing your tutorial:

http://www.raywenderlich.com/13541/how-to-create-an-app-like-instagram-with-a-web-service-backend-part-22

and there i have used your great great great JSONModel library, but i can't understand why in the code of that tutorial the compiler never enter in this method:

-(API*)init
{
//call super init
self = [super init];

if (self != nil) {
    //initialize the object
    user = nil;

    [self registerHTTPOperationClass:[AFJSONRequestOperation class]];

    // Accept HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
    [self setDefaultHeader:@"Accept" value:@"application/json"];
}

return self;
}

if never enter how you can set that header and the registerHTTPOperationClass? i try to insert a breakpoint there and never enter...

thanks!

Compiler warning about leaking problems for NSArray & NSDictionary

I'm having a bunch of compiler warning in my project (ARC enabled & XCode 4.6):

objc[29332]: Object 0x927e440 of class __NSArrayI autoreleased with no pool in place - just leaking - break on objc_autoreleaseNoPool() to debug
objc[29332]: Object 0x927e490 of class __NSArrayI autoreleased with no pool in place - just leaking - break on objc_autoreleaseNoPool() to debug
objc[29332]: Object 0x927fd10 of class __NSCFDictionary autoreleased with no pool in place - just leaking - break on objc_autoreleaseNoPool() to debug
objc[29332]: Object 0x927e3a0 of class __NSCFDictionary autoreleased with no pool in place - just leaking - break on objc_autoreleaseNoPool() to debug
objc[29332]: Object 0x927e3d0 of class __NSCFDictionary autoreleased with no pool in place - just leaking - break on objc_autoreleaseNoPool() to debug
objc[29332]: Object 0x927f340 of class __NSCFDictionary autoreleased with no pool in place - just leaking - break on objc_autoreleaseNoPool() to debug
objc[29332]: Object 0x927ff60 of class __NSCFDictionary autoreleased with no pool in place - just leaking - break on objc_autoreleaseNoPool() to debug

I added a symbolic breakpoint on objc_autoreleaseNoPool and the stack trace looks like this (for the first breakpoint):
Capture d e cran 2013-01-31 a 15 23 55

urlEncode and non NSStrings

Inside JSONHTTPClient.m I'm hitting an issue when I have any non NSStrings in my dictionary.

I'm not sure if there's supposed to be some conversion process before then (I'm relatively new to obj-c and just started using your library) but in the object I'm using I have a BOOL set to NO and a NSString set to NULL. In both cases the code runs up until it hits the urlEncode call inside of the syncRequestDataFromURL method.

I've gotten around it by adding the following to my code in the syncRequestDataFromURL params loop:

NSString *value;

if(![params[key] isKindOfClass: [NSString class]]) {
if(params[key] == [NSNull null]) {
value = @"null";
} else {
value = params[key];
}
} else {
value = [self urlEncode: params[key]];
}

[paramsString appendFormat:@"%@=%@&", key, value];

comparing models

It should be pretty straightforward to implement comparing of model objects.

Looks like a good idea in general to be able to "mark" a property as the model id. Like so:

@Property (strong, nonatomic) NSNumber<Index>* id;
or
@Property (strong, nonatomic) NSNumber<uid>* id;

so that the models will just compare the values of this property when compared.

Properties with @ in name

It's not possible to use JSONModel when the parsed json has properties with names containing @ or $ (and yes, some services do return these…). Any idea how to work around this problem?

migrate from exceptions to nserror

After reading extensively through the apple docs, I'll have to migrate from exceptions to using nserror. Pity - exceptions looked as the perfect way to handle nested models import errors.

Creating category for JSONValueTransformer leads to compiler warning.

I follow the instruction that creating category to override NSDateFromNSString method to handle different date time format.

Then the compiler warns "Category is implementing a method which will also be implemented by its primary class".

I did some research and find a way to suppress the warning by add: #pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation". But the linker is still warning...

Anyway, I think overriding those method by a subclass of JSONValueTransformer would be much better. Why not add a property to the JSONModel class that receive customized value transformer.

Mapping object from JSON response which has "description" key

I have a problem when map json response into class object. I have response like this

{
images": [
{
"url": "http://blabla.com/1344080_J.jpg",
"description": {
"en": "Exterior"
}
},
{
"url": "http://blabla.com/jo.jpg",
"description": {
"en": "Exterior View"
}
}]
}

@protocol ImagesModel
@EnD
@interface ImagesModel : JSONModel

@Property (strong,nonatomic)NSString *url;
@Property (strong,nonatomic)DescriptionModel *description;

@EnD

@interface DescriptionModel : JSONModel

@Property (strong,nonatomic)NSString *en;

@EnD

I got [DescriptionModel _stringRepresentation]: unrecognized selector sent to instance 0x7638030

I think the problem in "DescriptionModel *description", if I change that into "DescriptionModel *descriptions" it's ok but I don't get the real "description" from JSON. How do I solve this?

Confusion on root model if no name given

Hi,

I love your project, it makes JSON parsing so much simpler! I have a question though, how would I handle a JSON document that has no name associated? This is the entire document I am dealing with.

{
"class_id": "ADVMTG-1",
"class_pk": 10293,
"course": "Advisor Meeting",
"course_id": 7,
"course_type": "Advisory",
"description": "ADV: Abreu, E",
"group_fk": 13945,
"primary_grade_level": "None",
"school_level": "Upper School",
"school_year": 2012,
"status": "Active",
"subject": "Administration",
"teacher_fk": 393,
"teacher_full_name": "Eleodoro Abreu",
"update_date": "2012-10-23T10:06:00-05:00",
"teachers": [
    {
        "person_fk": 393,
        "role": "Primary Teacher",
        "role_id": 1,
        "teacher_name": "Eleodoro Abreu",
        "update_grades": true,
        "view_grades": true
    }
],
"meeting_times": [
    {
        "block": "Advisor Meetings",
        "block_abbreviation": "ADV",
        "day": "Friday",
        "end_time": null,
        "grading_period": "ALL",
        "room": null,
        "start_time": null
    }
]

}

By name associated I mean how "paging" below would be the root model:

{
"paging": {
    "page": 1,
    "total": 2931,
    "page_size": 20,
    "pages": 147
}

Support for subclasses?

Is it possible to create a conditional class?

E.g. I've got a JSON with firstname, lastname, organization. If organization is filled, I'd like to map it to a model of type Organization, otherwise to a Person - both subclasses of Contact, which itself is a subclass of JSONModel.

Is this possible or do I have to take all the properties into Contact?

What about struct like CGPoint and CGRect ?

Can those be used in models ?
I have tried with no luck creating a jsonValueTransformer.
One thing i noticed is that if a function with the name of my property is defined in my JSONModel class it will get called when saved.
ex

@interface MyClass : JSONModel

@property (nonatomic,strong) NSString* barPosition;

-(CGRect)getBarPosition;

crash on line 73 in JSONModel.m

hello Marin,

I'm trying to use this great framework !! but I receive an error on line 73 in JSONModel.m :

*** -[__NSDictionaryM respondsToSelector:]: message sent to deallocated instance 0x9b65d60

I use the following to create an object from a dictionary :

myObject = [[AnObject alloc] initWithDictionary:dict error:nil];

AnObject is an object of type JSONModel

(I don't use ARC & use version 0.7.8 of JSONModel)

Any suggestions ?

thanks
Frank

How to transform this json into json model

{“left”:”menu”,”sub”:[{"name":"News","controller":"xxxx"},{"name":"Top ","controller":"topctl"},{"name":"Map","controller":"mapctl"}],”center”:”gvctl”,”right”:”rightctl”}

How to deal with enums?

Let's say my model has this enum property:

typedef enum {
    StatusOpen,
    StatusClosed,
} Status;

@property (nonatomic) Status status;

If the status in the JSON is a string ("open" or "closed"), how can I transform from the string to the enum? It seems that JSONValueTransformer categories won't be called if it's not an object. Right now I'm saving the status as a NSString, and created a getter that does the transforming into the enum, but it's a bit weird.

Parsing error for strings in array

My web service provides an array of strings in the responded json. JSONModel fails to parse this array because of the assumption that the content of the array is a dictionary.

In
-(id)__transform:(id)value forProperty:(JSONModelClassProperty*)property
the debugger stops on line 520 value = [[protocolClass class] arrayOfModelsFromDictionaries: value]; where value is just a string. Am I'm missing something or is it a bug?

submodel array issue

here is my model, and json string is parsed with NSJSONSerialization

@interface MKSubModel : JSONModel
    @property (nonatomic, strong) NSString *name;
@end
@protocol MKSubModel @end

@interface MKModel : JSONModel
    @property (nonatomic, strong) NSString <Optional> *info;
    @property (nonatomic, strong) NSArray <Optional,MKSubModel> *people;
@end

however people seems not working as I expected so I have

MKModel *details = [[MKModel alloc] initWithDictionary:dict];
NSArray *people = details.people;

and this is where it fails:

for (MKSubModel *person in people)
{
     NSLog(@"%@",person.name); // exception 'NSInvalidArgumentException', reason: '-[__NSDictionaryM name]:
}

because person is NSDictionary, not MKSubModel type as expected.

static keyMappers dictionary is not thread safe?

When creating jsonmodel instances with many threads in parallel, the first initialization
of the static keymappers dictionary of a class appears to fail sporadically.

Best regards and thanks for this beautiful library!

Global JSONKeyMapper?

Hello ,
My API server using underscore naming in the json response, to magically rename the underscore to camelcase variable, i need to overwrite the JSONKeyMapper function like this

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

But this became quite tedious since i have many models. Is there any way to do global JSONKeyMapper instead write it one by one for each model?
(Probably kind of navigationbar appearance thing).

Thank you

Partial serialization

Anyway to partially serialize an object to JSON? I'm looking to only update specific fields in a network request.

Check JSON key for "self"

I'm using a JSON API which gives me back objects with keys named "self". Obviously this is a bad naming but I cannot change the API. Although Xcode lets me create a property with name self this smells bad.
One solution to this could be to check in your KeyMapper for the key "self" and replace it with something tbd. Or you can provide a hook for developers to implement their own mapping strategies.

Connecting the custom cell to the JSON

ACTUAL QUESTION: I am trying to retrieve a set of tweets using the JSONMODEL library and i am creating a custom cell for my table, but in order for the cell to display the tweets, it needs to be linked to the NSArray which is defined as a property in the STREAMVIEW.M, STREAMVIEW.H

In my first file where I declare a custom cell for the table view I request it like this:

_STREAMVIEW.M_

@synthesize masonryView;
@synthesize photos;
@synthesize screenWidth;
@synthesize tweets;


-(void)viewDidAppear:(BOOL)animated{

NSURL* url = [NSURL URLWithString:@"https://api.twitter.com/1/statuses/home_timeline.json?include_entities=true"];
NSURLRequest* request = [NSURLRequest requestWithURL:url];

AFJSONRequestOperation* op = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
    [self didReceiveJSON: JSON];
    NSLog(@"Fetched succesfully");
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
    NSLog(@"Floadt failed to connect");
}];

[op start];
}


-(void)didReceiveJSON:(NSDictionary*)obj{

NSArray* results = obj[@"results"];

@try {
    tweets = [TweetModel arrayOfDictionariesFromModels:results];
            NSLog(@"Fetched succesfully");

}
@catch (NSException *exception){
    NSLog(@"failed to fetch");

}

}

P.S. I created the tweets as an nonatomic,strong array(property) under the header file.

This is the file that creates the JSON Model that gets retrieved:

_TWEETMODEL.H_

#import "JSONModel.h"

@interface TweetModel : JSONModel

@property(strong,nonatomic) NSString* from_user_name;
@property(strong,nonatomic) NSString* profile_image_url;
@property(strong,nonatomic) NSString* text;

@end

Given these two files how would I link them to the actual custom cell file which i would create in the stream controller. The nsarray that i need to define in order to display a single tweet.

_VERTICALCELL.M_

#import "VerticalCell.h"
#import "Imports.h"

@implementation VerticalCell

- (void) updateCellInfo:(NSDictionary *)data {

TweetModel* tweet = tweets[indexPath.row];

self.text = tweet.text;
self.imageURL = tweet.profile_image_url;

[super updateCellInfo:data];
}

@end

description method of model containing an array

an array property in a model, is printed out like this in the console by NSLog:

   list: (
       "Person \n   name: john\n   age: 100\n   isFri...
   lastUpdate: 2013-03-07 07:34:48 +0000

Better to have a strcutured output

Compiler Warnings with Optional Properties

Hello,

Great work on this library. Having great success using the library. I am getting compiler warnings when trying to assign values into properties marked as

In my model I have:

@interface QLYListDetail : JSONModel
@Property (nonatomic, strong) QLYImage *thumbnailImage;
// more properties
@EnD

And elsewhere in my code I have:

QLYImage *t = [[QLYImage alloc] init];
self.shortList.thumbnailImage = t;

On the last line I have a warning:
"Incompatible pointer types assigning to 'QLYImage *' from 'QLYImage *__strong'"

Problem when saving NSMutableArray

I was having error when saving a model with a NSMutableArray like so

@property (nonatomic, strong) NSMutableArray<PresentationInfo>* presentations;

I think the problem might be in JSONModel.m in the function

-(id)__reverseTransform:(id)value forProperty:(JSONModelClassProperty*)property

I added the check for NSMutableArray at this line

if (property.type == [NSArray class] || property.type == [NSMutableArray class]) {

and now it works.

more allowedTypes

Consider add this types to allowed types

NSDecimalNumber
__NSArrayM
__NSArrayI
__NSDictionaryM
__NSDictionaryI

Problem receiving an array

First of all, thanks for this awesome library. I have one question, what would you do if you have an attribute that usually is an array, but the sender when is just one object, it will send to you as an specific object?. I will appreciate any kind of suggestion :)

instance variable optional

I want to make my Instance Variable like short to be Optional but xcode make error for this line
For Example:
@Property (nonatomic) short status;

What should I do?

Multidimensional array with unnamed entries

Hello,

I tried a lot of things, but I can't get it work. Is it possible to parse something like this from JSON to a model class? If yes, please tell me how.

            {
                "id": 490757198516,
                "height": 4,
                "width": 4,
                "gameField":
                [
                    [
                        {
                            "id": 13,
                            "pictureId": 6
                        },
                        {
                            "id": 3,
                            "pictureId": 1
                        }
                    ],
                    [
                        {
                            "id": 1,
                            "pictureId": 0
                        },
                        {
                            "id": 8,
                            "pictureId": 4
                        }
                    ]
                ]
            }

The gameField is a 2x2 array of GameField objects. In Java REST Service it is defined as "GameField gameField[2][2];" And GameField is a class with member variable "id" and "pictureId".

Best regards,
Mario

attr id i think modify to other

if i have

"id": 547662,
"name": "Johnbull's Group",

the id is system tag, i think if json have attr id,i think should modify it to other as id1

Validation not working?

If some of the items in my JSON source are missing required properties, then they should not be added to the array of objects when I call arrayOfModelsFromDictionaries, right?

See example project: https://github.com/kevinrenskers/JSONModelExample

As you can see, my JSON source (http://bladid.gangverk.is/user:8ad24ca53d75c29ccc7b814c2f96131d?json=1) has some articles with no titles. However, calling NSMutableArray *articles = [Article arrayOfModelsFromDictionaries:JSON[@"articles"]]; will contain some articles with no titles. How is that possible?

NSDate missing from allowedJSONTypes?

I was getting [JSONModel.m:243] Type __NSDate is not allowed in JSON. and nil returns for models with NSDate objects.

I could see there was date transforming support, so I just added [NSDate class] to allowedJSONTypes and now it works.

I would fork and submit a patch but it strikes me that I must be doing something wrong since I can't believe no-one has noticed! My date strings look like this:

"2013-07-01 00:07:32 +0000"

Am I missing something obvious or is the patch required?

Status Codes

Is there a way to handle different status codes back from an API. For instance, if the server returns a 401 for an expired/reset authentication token, or a 500 or server outage there is no way to tell the difference. Would it be possible to simply pass the error code up along with the JSONModelError?

Map from a item in array using JSONKeyMapper

For example:
I want to parse a response in Youtube api 2.0 to get the comments in a video and each comment entry in the response looks like:
sshot

I have a model with:
@Property (nonatomic,strong)NSString *authorName;
@Property (nonatomic,strong)NSString *publishedDate;
@Property (nonatomic,strong)NSString *comment;

and:
+(JSONKeyMapper*)keyMapper
{
return [[JSONKeyMapper alloc] initWithDictionary:@{
@"published.$t": @"publishedDate",
@"content.$t": @"comment
}];
}

How can i map the author name without creating a new object? the autor name in response is inside the first object in an array... i tried with @"author[0].name.$t": @"authorName" but don't seems to work.
btw, i'm using arrayOfModelsFromDictionaries to parse the youtube api response...

There is any simple way to map from a item in an array?

ARC test shouldn't be in the header file

There's no problem with the header files being included into a non-ARC project, as long as the implementation files are compiled with ARC, but the code in JSONModel.h:

#if !__has_feature(objc_arc)
#error The JSONMOdel framework is ARC only, you can enable ARC on per file basis.
#endif

Prevents this use case. I suggest moving it into the .m.

Property transformers

There seems to be no way to have a one-off transformer? Only from class to class, not from property to property?

Many other JSON to NSObject libraries allow you to create specially named methods so single properties can be transformed. With JSONModel, how would it for example be possible to transform a NSString to NSDate with a custom formatter? Create a subclass of JSONValueTransformer which then handles all NSString to NSDate transformations? That's too broad.

Receiving (null) when parsing Data

Hi once again! Thanks so much for the help last time. Sadly, I have another issue where the data being returned is null. This is my JSON data. And what I'm doing is creating a JSONModel called EnrollmentFeed with:

@property (strong, nonatomic) NSNumber* class_fk;    

And I am trying to get the output in NSLog, but I keep getting (null). Here's my implementation:

-(void)viewWillAppear:(BOOL)animated {
contentArray = [NSArray arrayWithContentsOfFile:[self dataFilePath]];
NSString *success = [contentArray objectAtIndex:0];

if ([success isEqualToString:@"success"]) {


//show loader view
[SVProgressHUD showProgress:10 status:@"Fetching JSON"];

//fetch the feed
_feed = [[EnrollmentFeed alloc] initFromURLWithString:url
                                     completion:^(JSONModel *model, JSONModelError *err) {

                                         //hide the loader view
                                         [SVProgressHUD showProgress:100 status:@"Done"];
                                         [SVProgressHUD dismiss];


                                         //json fetched
                                         NSLog(@"Enrollments: %@", _feed.class_fk);

                                     }];

} else {
    NSLog(@"Failed because not logged in");
    [SVProgressHUD showErrorWithStatus:@"Try Logging in First!"];
} }

JSON Data:

[
{
    "class_fk": 10326,
    "currently_enrolled": true,
    "date_withdrawn": null,
    "enrollment_pk": 147745,
    "fee_paid": false,
    "late_date_enrolled": null,
    "level": null,
    "student_fk": 132664,
    "update_date": "2012-08-27"
},
{
    "class_fk": 10371,
    "currently_enrolled": true,
    "date_withdrawn": null,
    "enrollment_pk": 147168,
    "fee_paid": false,
    "late_date_enrolled": null,
    "level": null,
    "student_fk": 132664,
    "update_date": "2012-08-23"
},
{
    "class_fk": 11049,
    "currently_enrolled": true,
    "date_withdrawn": null,
    "enrollment_pk": 150397,
    "fee_paid": false,
    "late_date_enrolled": null,
    "level": null,
    "student_fk": 132664,
    "update_date": "2013-03-28"
}
]

Core Data

Hello,

Is there some way to use JSONModel do create Core Data objects?
The only way I can think is to let JSONModel handle all the JSON work and then copy all the fields to a custom NSManagedObject if the conversion was successful… or is there another way to create the NSManagedObject that I'm not aware of?

Thanks!

Attribute Mapping

I love how lightweight this is. The only issue I have is that I want to map underscore attribute names from rails (ie hair_color) to a more iOS friendly camel case (ie hairColor). Any plans for that?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.