iOS中如何将嵌套Model类对象作为JSON API参数传递?
解决iOS Model转JSON作为API参数的方法
嘿,这个场景我太熟悉了!要把包含嵌套Model的对象转成JSON作为API参数,主要有几种方案,看你偏好哪种:
一、手动转换(无第三方依赖)
如果不想引入第三方库,自己写字典转换逻辑最稳妥,能完全控制每个字段的输出:
- 先给
locationModel添加转字典的方法:
@implementation locationModel - (NSDictionary *)toDictionary { // 处理nil值,避免转JSON时出错 NSString *latStr = self.Lat ?: @""; NSString *lngStr = self.Lng ?: @""; return @{@"Lat": latStr, @"Lng": lngStr}; } @end
- 给
userModel添加对应的转字典方法,嵌套调用locationModel的转换:
@implementation userModel - (NSDictionary *)toDictionary { NSMutableDictionary *resultDict = [NSMutableDictionary dictionary]; // 处理uName的nil情况 resultDict[@"uName"] = self.uName ?: @""; // 如果location对象存在,才添加到字典里 if (self.mLocation) { resultDict[@"mLocation"] = [self.mLocation toDictionary]; } return resultDict; } @end
- 最后把字典转成JSON格式(字符串或Data,根据API需求选择):
userModel *objUserModel = [[userModel alloc] init]; // 先给objUserModel赋值... NSDictionary *userDict = [objUserModel toDictionary]; NSError *jsonError = nil; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:userDict options:NSJSONWritingPrettyPrinted error:&jsonError]; if (!jsonError) { // 如果API需要JSON字符串 NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; NSLog(@"最终JSON:%@", jsonString); // 把jsonString或jsonData作为参数传给API即可 } else { NSLog(@"转JSON失败:%@", jsonError.localizedDescription); }
二、用第三方库简化操作(推荐)
如果项目里允许引入第三方库,用成熟的Model转JSON工具能省超多代码,比如MJExtension或者YYModel:
示例:用MJExtension
- 先通过CocoaPods引入:
pod 'MJExtension'
- 直接调用库的方法转换:
userModel *objUserModel = [[userModel alloc] init]; // 赋值... // 转成字典 NSDictionary *userDict = [objUserModel mj_keyValues]; // 直接转成JSON字符串 NSString *jsonString = [objUserModel mj_JSONString]; // 转成NSData的话,也可以用系统方法从字典转换 NSData *jsonData = [NSJSONSerialization dataWithJSONObject:userDict options:0 error:nil];
示例:用YYModel
- 引入库:
pod 'YYModel'
- 转换代码:
userModel *objUserModel = [[userModel alloc] init]; // 赋值... // 转字典 NSDictionary *userDict = [objUserModel yy_modelToJSONObject]; // 转JSON字符串 NSString *jsonString = [objUserModel yy_modelToJSONString];
这些第三方库会自动处理嵌套Model、nil值、属性名映射(如果API字段名和Model属性名不一样的话),非常省心!
注意事项
- 系统的
NSJSONSerialization只能序列化基础类型(字符串、数字、数组、字典),不能直接传Model对象,所以必须先转成字典。 - 处理nil值很重要,避免转JSON时抛出异常,手动转换要判断,第三方库一般会自动把nil转成空字符串或忽略该字段(根据库的配置)。
内容的提问来源于stack exchange,提问作者Nirav Zalavadia




