如何将GoogleSignIn的GIDGoogleUser(ObjC对象)转为字典?
将GIDGoogleUser转为字典的可行方案
针对你需要把GIDGoogleUser对象转为字典、无需手动编写全量解析逻辑的需求,以下几种方案可以直接使用:
1. 利用Objective-C运行时自动遍历属性
通过OC运行时API,可以自动获取对象的所有属性并生成字典,无需手动逐个字段编写解析代码,适合需要完整导出所有用户资料的场景。
实现代码如下:
#import <objc/runtime.h> NSDictionary *objectToDictionary(id object) { if (!object) return nil; NSMutableDictionary *resultDict = [NSMutableDictionary dictionary]; unsigned int propertyCount; objc_property_t *properties = class_copyPropertyList([object class], &propertyCount); for (NSUInteger i = 0; i < propertyCount; i++) { objc_property_t property = properties[i]; NSString *propertyName = [NSString stringWithUTF8String:property_getName(property)]; id propertyValue = [object valueForKey:propertyName]; // 处理基础可序列化类型 if ([propertyValue isKindOfClass:[NSString class]] || [propertyValue isKindOfClass:[NSNumber class]] || [propertyValue isKindOfClass:[NSArray class]] || [propertyValue isKindOfClass:[NSDictionary class]]) { resultDict[propertyName] = propertyValue; } // 处理自带转字典方法的子对象(比如GIDProfileData) else if ([propertyValue respondsToSelector:@selector(dictionaryRepresentation)]) { resultDict[propertyName] = [propertyValue performSelector:@selector(dictionaryRepresentation)]; } // 其他类型转为字符串避免序列化失败 else { resultDict[propertyName] = [NSString stringWithFormat:@"%@", propertyValue]; } } free(properties); return resultDict; }
使用方式:
// 假设googleUser是授权成功后得到的GIDGoogleUser实例 NSDictionary *userDict = objectToDictionary(googleUser);
2. 利用GIDGoogleUser官方API提取结构化数据
如果不需要导出所有私有属性,只需要官方公开的用户资料,直接调用GIDGoogleUser及其子对象的公开方法即可,这种方式更稳定,不会因谷歌SDK内部属性变动出问题:
NSMutableDictionary *userDict = [NSMutableDictionary dictionary]; // 导出用户基础资料(包含姓名、邮箱、头像等) userDict[@"profile"] = googleUser.profile.dictionaryRepresentation; // 导出认证相关信息 userDict[@"auth_info"] = @{ @"access_token": googleUser.authentication.accessToken ?: @"", @"id_token": googleUser.authentication.idToken ?: @"", @"refresh_token": googleUser.authentication.refreshToken ?: @"", @"expiration_date": [googleUser.authentication.expirationDate description] ?: @"" }; // 导出用户唯一ID userDict[@"user_id"] = googleUser.userID;
3. 利用NSKeyedArchiver快速归档转字典(不推荐)
这种方式可以快速将对象转为字典,但会包含大量冗余的类信息,且部分属性可能因不支持归档导致失败,仅适合临时测试场景:
NSError *error = nil; NSData *archiveData = [NSKeyedArchiver archivedDataWithRootObject:googleUser requiringSecureCoding:NO error:&error]; if (!error) { NSDictionary *userDict = [NSKeyedUnarchiver unarchiveObjectWithData:archiveData]; }
注意事项
- 运行时方案会遍历所有属性(包括私有属性),发送到后端前请检查字典内容,避免泄露敏感或不必要的数据;
- 如果是Swift项目调用上述OC代码,需要在桥接文件中导入包含工具方法的头文件;
- 若遇到子对象无法序列化的情况,可在运行时方法中添加递归转换逻辑,确保所有嵌套对象都能转为字典或字符串。
内容的提问来源于stack exchange,提问作者user121095
相关产品推荐
相关产品推荐

