How to convert this JSON save to realm database

1,087 views
Skip to first unread message

Trung Hiếu Vũ

unread,
Nov 13, 2014, 10:38:28 PM11/13/14
to realm...@googlegroups.com
How to convert JSON format like this  to dictionary and save to realm.Thanks in advanced

{
  "collections": [
    {
      "id": 1,
      "name": "Pumpkin",
      "description": "Halloween is coming. Yay!",
      "number_of_stamps": 10,
      "urls": [
      ]
    },
    {
      "id": 2,
      "name": "Cake",
      "description": "Does Panda like to eat cakes? All sweet cakes for him here.",
      "number_of_stamps": 20,
      "urls": [
      ]
    }
  ]
}

JP Simard

unread,
Nov 17, 2014, 12:58:45 PM11/17/14
to Trung Hiếu Vũ, realm...@googlegroups.com
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

--
You received this message because you are subscribed to the Google Groups "Realm" group.
To unsubscribe from this group and stop receiving emails from it, send an email to realm-cocoa...@googlegroups.com.
To post to this group, send email to realm...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/realm-cocoa/8696dbf9-e8d9-4238-8f9e-cf9ca8bdf151%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages