stig/json-framework — Issue #110: stringWithObject fails for NSManagedObject subclass
Author: ghulammustafa
Created: 2011-11-14 11:08:42+00:00
State: open

I want to convert my core-data object graph to json. I have two NSManagedObject subclasses i.e. ParentManagedObjectClass, and ChildManagedObjectClass. They have a one-to-many relationship. I implemented - (id)proxyForJson; in both the managed object subclasses, _but it's not executed_.

Here's a sample code:

ParentManagedObjectClass *myParentManagedObject = ...;

SBJsonWriter *writer = [SBJsonWriter new];
NSString *jsonString = [writer stringWithObject:self.myParentManagedObject];
[writer release];

As a result, i get nil in jsonString.

Note: Something similar to below might work, but it's completely generic and doesn't allow customization i.e. i want to use only selected attributes for my json.

@implementation NSManagedObject (NSManagedObject_JSON)

/*
*
* This method is implemented to help NSObject+JSON with transforming to JSON as per SBJSON's JSONValue helper method.
*
*/
-(NSDictionary*) proxyForJson {
NSDictionary * attributes = [[self entity] attributesByName];
NSDictionary * relationships = [[self entity] relationshipsByName];

NSMutableDictionary * results = [NSMutableDictionary dictionary];

for (NSString * relationship in [relationships keyEnumerator]) {
id value = [self valueForKey:relationship];
if(value) {
if([value isKindOfClass:[NSSet class]]) {
[results setObject:[(NSSet*)value allObjects] forKey:relationship];
}
else {
[results setObject:value forKey:relationship];
}
}
}

for (NSString * attribute in [attributes keyEnumerator]) {
id value = [self valueForKey:attribute];
if(value) {
[results setObject:value forKey:attribute];
}
}

return results;
}

@end