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.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

toJSONString is not working when nested models exist

iManiaq opened this issue · comments

These are the two models I have :

@interface Category : JSONModel
@property (nonatomic) NSInteger catId;
@property (nonatomic) NSString *categoryName;
@property (nonatomic) float size;
@property (nonatomic) NSArray<Sticker *> * stickersArray;
@end
@interface Sticker : JSONModel
@property (nonatomic) NSInteger stickerId;
@property (nonatomic) NSString *stickerName;
@property (nonatomic) float size;
@end
- (void)createObjectAndMapToJson
{
    Sticker *stick1 = [[Sticker alloc] init];
    stick1.stickerName = @"sticker1";
    stick1.stickerId = 123;
    stick1.size = 12.33;

    Sticker *stick2 = [[Sticker alloc] init];
    stick2.stickerName = @"sticker23";
    stick2.stickerId = 3323;
    stick2.size = 4.33;
    
    Category *catObj = [[Category alloc] init];
    catObj.catId = 111102;
    catObj.categoryName = @"My category";
    catObj.size = 1233.44;
    catObj.stickersArray = @[stick1, stick2];

    NSLog(@"%@", [catObj toJSONString]);  
}

It fails with error : [JSONModel.m:1058] EXCEPTION: Invalid type in JSON write (Sticker

@property (nonatomic) NSArray<Sticker *> * stickersArray;

This is not correct - it will not work. You can do either of these:

@property (nonatomic) NSArray<Sticker *> <Sticker> *stickersArray;

or

@property (nonatomic) NSArray <Sticker> *stickersArray;

You must also define the Sticker protocol:

@protocol Sticker;

See: https://github.com/jsonmodel/jsonmodel#model-collections

It works so awesome , Thanks a lot for such a quick reply

Does anyone know how do you handle this issue when you also want it to be Optional. That is that array could also be null.
@billinghamj

@property (nonatomic) NSArray<Sticker *> <Sticker, Optional> *stickersArray;

Yep. Got it. Thanks for that.