Created
April 12, 2012 20:31
-
-
Save dchohfi/2370777 to your computer and use it in GitHub Desktop.
JSON automatic parser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// JSONParser.m | |
// BusaoSP | |
// | |
// Created by Diego Chohfi on 4/12/12. | |
// Copyright (c) 2012 None. All rights reserved. | |
// | |
#import "JSONParser.h" | |
#import <objc/runtime.h> | |
@implementation JSONParser | |
+ (id) parseJson: (NSDictionary *) json forClass: (Class) class{ | |
#pragma clang diagnostic push | |
#pragma clang diagnostic ignored "-Warc-performSelector-leaks" | |
NSObject *object = [[class alloc] init]; | |
NSArray *keys = [json allKeys]; | |
for (NSString *key in keys) { | |
id<NSObject> value = [json valueForKey:key]; | |
if ([value isKindOfClass:[NSArray class]]) { | |
continue; | |
}else{ | |
objc_property_t property = class_getProperty(class, [key UTF8String]); | |
if (property) { | |
if([value isKindOfClass:[NSDictionary class]]){ | |
NSString *className = [NSString stringWithUTF8String:getPropertyType(property)]; | |
value = [self parseJson:(NSDictionary *) value forClass:NSClassFromString(className)]; | |
} | |
NSError *error; | |
if([object validateValue:&value forKey:key error:&error]){ | |
[object setValue:value forKey:key]; | |
} | |
} | |
} | |
} | |
#pragma clang diagnostic pop | |
return object; | |
} | |
static const char *getPropertyType(objc_property_t property) { | |
const char *attributes = property_getAttributes(property); | |
char buffer[1 + strlen(attributes)]; | |
strcpy(buffer, attributes); | |
char *state = buffer, *attribute; | |
while ((attribute = strsep(&state, ",")) != NULL) { | |
if (attribute[0] == 'T') { | |
return (const char *)[[NSData dataWithBytes:(attribute + 3) length:strlen(attribute) - 4] bytes]; | |
} | |
} | |
return "@"; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment