Objective-c 自定对象 转 JSON

来源:互联网 发布:科比安东尼西决数据 编辑:程序博客网 时间:2024/06/05 17:18

#pragma mark - NSObject to JSON -


static NSDateFormatter *reverseFormatter;


- (NSDateFormatter *)getReverseDateFormatter {

    if (!reverseFormatter) {

        NSLocale *locale = [[NSLocalealloc] initWithLocaleIdentifier:@"en_US_POSIX"];

        reverseFormatter = [[NSDateFormatteralloc] init];

        [reverseFormattersetDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];

        [reverseFormatter setLocale:locale];

    }

    returnreverseFormatter;

}


- (NSDictionary *)dictionaryWithPropertiesOfObject:(id)obj {

    NSMutableDictionary *dict = [NSMutableDictionarydictionary];

    

    unsigned count;

    objc_property_t *properties =class_copyPropertyList([obj class], &count);

    

    for (int i =0; i < count; i++) {

        NSString *key = [NSStringstringWithUTF8String:property_getName(properties[i])];

        id object = [obj valueForKey:key];

        

        if (object) {

            if ([object isKindOfClass:[NSArray class]]) {

                NSMutableArray *subObj = [NSMutableArrayarray];

                for (id oin object) {

                    [subObj addObject:[selfdictionaryWithPropertiesOfObject:o]];

                }

                dict[key] = subObj;

            }

            else if ([object isKindOfClass:[NSStringclass]]) {

                dict[key] = object;

            } else if ([object isKindOfClass:[NSDateclass]]) {

                dict[key] = [[selfgetReverseDateFormatter] stringFromDate:(NSDate *) object];

            } else if ([object isKindOfClass:[NSNumberclass]]) {

                dict[key] = object;

            } else if ([[object class] isSubclassOfClass:[NSObjectclass]]) {

                dict[key] = [selfdictionaryWithPropertiesOfObject:object];

            }

        }

        

    }

    return dict;

}

原创粉丝点击