« Asynchronous unit testing with OCMock | Main | Anthony Burch rants on indie games »
Sunday
Oct252009

Turn Core Data models into JSON

Json is a lightweight data-interchange format, says the official website. Think XML but with a format that's easier for both people and javascript interpreters to parse. Here's an easy way to serialize Core Data models into json.

First, download blakeseely's bsjonadditions project and include the source in your xcode project. Secondly, copy & paste the following snippet into a new file in your project called NSManagedObjectExtras.m:

//
//  NSManagedObjectExtras.m
//

#import "NSDictionary+BSJSONAdditions.h"
#import "NSArray+BSJSONAdditions.h"


@implementation NSManagedObject (NSObject)

- (NSDictionary *)propertiesDictionary
{
  NSMutableDictionary *properties = [[[NSMutableDictionary alloc] init] autorelease];

  for (id property in [[self entity] properties])
  {
    if ([property isKindOfClass:[NSAttributeDescription class]])
    {
      NSAttributeDescription *attributeDescription = (NSAttributeDescription *)property;
      NSString *name = [attributeDescription name];
      [properties setValue:[self valueForKey:name] forKey:name];
    }

    if ([property isKindOfClass:[NSRelationshipDescription class]])
    {
      NSRelationshipDescription *relationshipDescription = (NSRelationshipDescription *)property;
      NSString *name = [relationshipDescription name];

      if ([relationshipDescription isToMany])
      {
        NSMutableArray *arr = [properties valueForKey:name];
        if (!arr)
        {
          arr = [[[NSMutableArray alloc] init] autorelease];
          [properties setValue:arr forKey:name];
        }

        for (NSManagedObject *o in [self mutableSetValueForKey:name])
          [arr addObject:[o propertiesDictionary]];
      }
      else
      {
        NSManagedObject *o = [self valueForKey:name];
        [properties setValue:[o propertiesDictionary] forKey:name];
      }
    }
  }

  return properties;
}  

- (NSString *)jsonStringValue
{
  return [[self propertiesDictionary] jsonStringValue];
}

@end

Now all you need to do is to call [coreDataModel jsonStringValue] to get the model as a json string.

PrintView Printer Friendly Version

EmailEmail Article to Friend

Reader Comments (2)

Sweet! Thanks for sharing this.

-jcr

October 25, 2009 | Unregistered CommenterJohn C. Randolph

I'm trying to gett his to work, and I've followed the instructions carefully (I had to add #import <CoreData/CoreData.h> at the top of NSManagedObjectExtras.m)

but how do I construct the 'coreDataModel' variable for the call [coreDataModel jsonStringValue] ? What type is it? Can you post an example please.

November 17, 2009 | Unregistered CommenterPeter Brooke
Comments for this entry have been disabled. Additional comments may not be added to this entry at this time.