.h文件——————————————
#import
@interfaceObjectToJSON :NSObject
+ (NSString*)objectTOJSON:(id)obj;
@end
.m文件中————————————————————
#import"ObjectToJSON.h"
#import
@implementationObjectToJSON
+ (NSString*)objectTOJSON:(id)obj {
NSDictionary*dict = [selfgetObjectData:obj];
return[selfdataTOjsonStringWithDictionary:dict];
}
+ (NSDictionary*)getObjectData:(id)obj {
NSMutableDictionary*dic = [NSMutableDictionarydictionary];
unsignedintpropsCount;
objc_property_t*props =class_copyPropertyList([objclass], &propsCount);
for(inti =0;i < propsCount; i++) {
objc_property_tprop = props[i];
NSString*propName = [NSStringstringWithUTF8String:property_getName(prop)];
idvalue = [objvalueForKey:propName];
if(value ==nil) {
value = [NSNullnull];
}else{
value = [selfgetObjectInternal:value];
}
// 如果自定义的对象中有关键字,可以在这里进行修改
if([propNameisEqualToString:@"ID"]) {
propName =@"id";
}
if([propNameisEqualToString:@"descrip"]) {
propName =@"description";
}
[dicsetObject:valueforKey:propName];
}
returndic;
}
+ (id)getObjectInternal:(id)obj {
if([objisKindOfClass:[NSStringclass]]
||
[objisKindOfClass:[NSNumberclass]]
||
[objisKindOfClass:[NSNullclass]]) {
returnobj;
}
if([objisKindOfClass:[NSArrayclass]]) {
NSArray*objarr = obj;
NSMutableArray*arr = [NSMutableArrayarrayWithCapacity:objarr.count];
for(inti =0; i < objarr.count; i++) {
[arr setObject:[selfgetObjectInternal:[objarr objectAtIndex:i]] atIndexedSubscript:i];
}
returnarr;
}
if([obj isKindOfClass:[NSDictionary class]]) {
NSDictionary *objdic = obj;
NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:[objdic count]];
for(NSString *keyinobjdic.allKeys) {
[dic setObject:[selfgetObjectInternal:[objdic objectForKey:key]] forKey:key];
}
returndic;
}
return[selfgetObjectData:obj];
}
+ (NSString*)dataTOjsonStringWithDictionary:(NSDictionary *)object
{
NSString *jsonString =nil;
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object
options:NSJSONWritingPrettyPrinted
error:&error];
if(! jsonData) {
NSLog(@"Got an error: %@", error);
}else{
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
returnjsonString;
}
@end