我需要将JSON字符串反序列化为自定义复杂对象。将NSDictionary对象转换为自定义复杂对象
例如可以说我有JSON字符串:
{"Menu": {
"categoryList": {
"Category": [
{"name": "Cat1"},
{"name": "Cat1"},
{"name": "Cat3"}
]
}
}}
我如何反序列化这个字符串初始化具有所属分类包括类型类别类3类对象菜单对象?有什么办法可以做到这一点?
我需要将JSON字符串反序列化为自定义复杂对象。将NSDictionary对象转换为自定义复杂对象
例如可以说我有JSON字符串:
{"Menu": {
"categoryList": {
"Category": [
{"name": "Cat1"},
{"name": "Cat1"},
{"name": "Cat3"}
]
}
}}
我如何反序列化这个字符串初始化具有所属分类包括类型类别类3类对象菜单对象?有什么办法可以做到这一点?
尝试使用JSON解析器。
http://code.google.com/p/json-framework/
它会分析你的字符串,并退给你,表示你的数据一个NSObject(NSArray的NSDictionary的或)。
编辑:
那么,作为OP希望得到一个自定义对象,而不是一个NSDictionary/NSArray的,它可以实现的东西,如下(假设做太困难会得到正确的数据,并设置每个新对象的属性)
基础上code provided by @andrewsardone,人们可以利用志愿来获得与相应地设置属性的新对象,处理JSON与任何解决方案解析后容易实现的功能适合您的项目更好地
+(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];
}
这是一个所需的功能,似乎没有一个好的(公共)解决方案。
nsarray和nsdictionary不是自定义对象 – 2012-12-19 03:40:43
@rocity所以,我最后的编辑添加了自定义对象的解决方案,这似乎是OP正在寻找 – 2013-01-21 12:27:35