I need to deserialize JSON string to custom complex objects.
For example lets say I have the json string:
{"Menu": {
"categoryList": {
"Category": [
{"name": "Cat1"},
{"name": "Cat1"},
{"name": "Cat开发者_运维知识库3"}
]
}
}}
How can I deserialize this string to initialize a Menu object that has a categoryList which includes 3 category objects of type Category class? Is there any way to to this?
This is a needed capability for which there does not seem to exist a good (public) solution.
Try using a JSON parser.
http://code.google.com/p/json-framework/
It will analyse your string and give you back an NSObject (NSArray or NSDictionary) that represents your data.
EDIT:
Well, as the OP wanted to get a custom object instead of an NSDictionary/NSArray, it could be implemented something as the following (assuming that the dificulty would get the correct data and set each of the new object properties)
Based on the code provided by @andrewsardone, one could easily implement a function using KVO to get a new object with the properties set accordingly, after handling the JSON parsing with whatever solution fits your project better
+(id) objectFromDictionary:(NSDictionary *)dict {
id entry = [[self alloc] init];
Class aClass = [entry class];
do {
unsigned int outCount, i;
objc_property_t *properties = class_copyPropertyList(aClass, &outCount);
for (i = 0; i < outCount; i++) {
objc_property_t property = properties[i];
NSString *propertyName = [[[NSString alloc] initWithCString:property_getName(property) encoding:NSUTF8StringEncoding] autorelease];
id propertyValue = [dict objectForKey:propertyName];
if (propertyValue && ![propertyValue isEqual:[NSNull null]]) {
[entry setValue:propertyValue forKey:propertyName];
}
}
free(properties);
//added to take care of the class inheritance
aClass = [aClass superclass];
} while (![[[aClass class] description] isEqualToString:[NSObject description]]);
return [entry autorelease];
}
精彩评论