Sunday
Oct252009
Turn Core Data models into JSON
Sunday, October 25, 2009 at 9:19AM 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.
Comments Off |
tagged
programming,
tutorial
programming,
tutorial
Reader Comments (2)
Sweet! Thanks for sharing this.
-jcr
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.