Hi Trung, here's one way you could model and map your JSON to Realm objects:
@interface MYURL : RLMObject
@property NSString *urlString;
@end
@implementation MYURL
@end
RLM_ARRAY_TYPE(MYURL)
@interface MYCollection : RLMObject
@property NSInteger id;
@property NSString *name;
@property NSString *descriptionString;
@property NSInteger number_of_stamps;
@property NSString *preview;
@property NSString *thumbnail;
@property RLMArray<MYURL> *urls;
@end
@implementation MYCollection
@end
Note that we've mapped the "description" key in your JSON to a "descriptionString" property to avoid colliding with NSObject's readonly description property. We've also "boxed" your URL strings in a MYURL object, since RLMArray properties can only contain RLMObject's. So a direct array of strings isn't supported.
As for the mapping code, this works:
// Import JSON
NSString *jsonFilePath = [[NSBundle mainBundle] pathForResource:@"collections" ofType:@"json"];
NSData *jsonData = [NSData dataWithContentsOfFile:jsonFilePath];
NSError *error = nil;
NSArray *collectionDicts = [[NSJSONSerialization JSONObjectWithData:jsonData
options:0
error:&error] objectForKey:@"collections"];
if (error) {
NSLog(@"There was an error reading the JSON file: %@", error.localizedDescription);
return 1;
}
RLMRealm *realm = [RLMRealm defaultRealm];
[realm beginWriteTransaction];
// Add Collection objects in realm for every collection dictionary in JSON array
for (NSDictionary *collectionDict in collectionDicts) {
NSMutableDictionary *mCollectionDict = [collectionDict mutableCopy];
mCollectionDict[@"descriptionString"] = collectionDict[@"description"];
[mCollectionDict removeObjectForKey:@"description"];
NSArray *urlsArray = collectionDict[@"urls"];
NSMutableArray *mUrlsArray = [NSMutableArray arrayWithCapacity:urlsArray.count];
for (NSString *urlString in urlsArray) {
[mUrlsArray addObject:@[urlString]];
}
mCollectionDict[@"urls"] = mUrlsArray;
[MYCollection createInDefaultRealmWithObject:mCollectionDict];
}
[realm commitWriteTransaction];
// Print all collections from realm
for (MYCollection *collection in [MYCollection allObjects]) {
NSLog(@"collection in realm: %@", collection);
}
So we parse the JSON with NSJSONSerialization. Then for each collection dictionary, we map description to descriptionString and the array of URL strings to an array of arrays of URL strings. This last step is the boxing we mentioned earlier. Each subarray containing the URL string represents an array of property values for our MYURL model.
Please let us know if there's anything else we can do to help :)
JP