Skip to content

Commit

Permalink
add JSON parsing methods for rootless JSON
Browse files Browse the repository at this point in the history
  • Loading branch information
Josh Vickery committed Apr 20, 2009
1 parent 4700f44 commit a029e5a
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
Expand Up @@ -12,6 +12,7 @@
@interface NSObject (JSONSerializableSupport) <JSONSerializable>

+ (id)fromJSONData:(NSData *)data;
+ (id) deserializeJSON:(id)jsonObject asClass:(Class) claz;
- (NSString *)toJSON;
- (NSString *)toJSONExcluding:(NSArray *)exclusions;
- (NSString *)toJSONAs:(NSString *)rootName;
Expand Down
37 changes: 37 additions & 0 deletions Classes/lib/Serialization/JSON/NSObject+JSONSerializableSupport.m
Expand Up @@ -57,6 +57,43 @@ + (id) propertyClass:(NSString *)className {
return NSClassFromString([className toClassName]);
}

+ (id) deserializeJSON:(id)jsonObject asClass:(Class) claz {
id result = nil;

if ([jsonObject isKindOfClass:[NSArray class]]) {
//JSON array
result = [NSMutableArray array];
for (id childObject in jsonObject) {
[result addObject:[self deserializeJSON:childObject asClass:claz]];
}
}
else if ([jsonObject isKindOfClass:[NSDictionary class]]) {
//this assumes we are dealing with JSON dictionaries without class names
// { property1 : value, property2 : {property 3 : value }}
result = [[[claz alloc] init] autorelease];

NSDictionary *objectPropertyNames = [claz propertyNamesAndTypes];

for (NSString *property in [jsonObject allKeys]) {
NSString *propertyCamalized = [property camelize];
if ([[objectPropertyNames allKeys] containsObject:propertyCamalized]) {
Class propertyClass = [self propertyClass:[objectPropertyNames objectForKey:propertyCamalized]];
if ([[NSDictionary class] isSubclassOfClass:propertyClass]) {
[result setValue:[jsonObject objectForKey:property] forKey:propertyCamalized];
}
else {
[result setValue:[self deserializeJSON:[propertyClass deserializeJSON:[jsonObject objectForKey:property] asClass:propertyClass]] forKey:propertyCamalized];
}
}
}
}
else {
//JSON value
result = jsonObject;
}
return result;
}

+ (id) deserializeJSON:(id)jsonObject {
id result = nil;
if ([jsonObject isKindOfClass:[NSArray class]]) {
Expand Down

0 comments on commit a029e5a

Please sign in to comment.