我的 MyModel 继承自 MTLModel(使用 GitHub Mantle pod)。 我的模型.h
#import <Mantle/Mantle.h>
@interface MyModel : MTLModel <MTLJSONSerializing>
@property (nonatomic, copy, readonly) NSString *UUID;
@property (nonatomic, copy) NSString *someProp;
@property (nonatomic, copy) NSString *anotherProp;
@end
我的模型.m
#import "MyModel.h"
@implementation MyModel
+ (NSDictionary *)JSONKeyPathsByPropertyKey
{
return @{
@"UUID": @"id",
@"someProp": @"some_prop",
@"anotherProp": @"another"
};
}
}
@end
现在我想使用 AFNetworking 将 JSON 发送到后端。在此之前,我将模型实例转换为 JSON NSDictionary,以用作请求中的参数/正文有效负载。
NSDictionary *JSON = [MTLJSONAdapter JSONDictionaryFromModel:myModel];
但是这个 JSON 包含奇怪的“”字符串,表示我的模型的属性为 nil。相反,我想要的是 Mantle 省略这些键/值对,只输出一个 JSON,其中只有不是 nil 或 NSNull.null 的属性。
最佳答案
这是 Mantle 的一个常见问题,称为隐式 JSON 映射。
MTLJSONAdapter
读取模型的所有属性以创建一个 JSON 字符串,可选择将属性名称替换为 +JSONKeyPathsByPropertyKey
中给出的名称。
如果您希望从模型的 JSON 表示中排除某些属性,请将它们映射到 +JSONKeyPathsByPropertyKey
中的 NSNull.null
:
+ (NSDictionary *)JSONKeyPathsByPropertyKey {
return @{
@"UUID": @"id",
@"someProp": @"some_prop",
@"anotherProp": @"another",
@"myInternalProperty": NSNull.null,
@"myAnotherInternalProperty": NSNull.null,
};
}
隐式 JSON 映射最近成为一个值得注意的问题,目前正在 GitHub 的 Mantle 主存储库中讨论解决方案。
查看问题 #137 , #138 , #143以及当前在 #149 下的讨论.
编辑:我显然误解了这个问题,但现在,当我想我理解正确时,答案很简单。
MTLJSONAdapter
使用 MTLModel
的 dictionaryValue
属性生成 JSON 数据。如果您希望从 JSON 本身中排除某个属性,您可以在 MYModel
中覆盖该方法:
- (NSDictionary *)dictionaryValue {
NSMutableDictionary *originalDictionaryValue = [[super dictionaryValue] mutableCopy];
if (self.aPropertyThatShouldBeExcludedWhenNil == nil) {
[originalDictionaryValue removeObjectForKey:@"aPropertyThatShouldBeExcludedWhenNil"];
}
/* repeat the process for other "hidden" properties */
return originalDictionaryValue;
}
编辑#2:检查删除所有 nil
值的代码*:
- (NSDictionary *)dictionaryValue {
NSMutableDictionary *modifiedDictionaryValue = [[super dictionaryValue] mutableCopy];
for (NSString *originalKey in [super dictionaryValue]) {
if ([self valueForKey:originalKey] == nil) {
[modifiedDictionaryValue removeObjectForKey:originalKey];
}
}
return [modifiedDictionaryValue copy];
}
* - matths 建议的代码示例。
关于ios - 如何使用 Mantle 省略 JSON 字典中的空值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18961622/