【问题标题】:Match JSON using RestKit using KVC Validation使用 RestKit 使用 KVC Validation 匹配 JSON
【发布时间】:2014-09-25 01:03:19
【问题描述】:

我有这个 JSON(字典数组):

[
    {"id":"BTCLTC","last":"89.767","high":"96.185","low":"25.000","bid":"89.729","ask":"91.320","volume":"29.78918","scale":3},
    {"id":"BTCUSD","last":"443.799","high":"444.092","low":"394.570","bid":"439.110","ask":"446.760","volume":"4.68266","scale":3},
    {"id":"BTCXRP","last":"98101.500","high":"98101.500","low":"86000.000","bid":"94999.050","ask":"97499.900","volume":"21.66779","scale":3}
]

例如,我想使用RKObjectMappingMatcher 来匹配"id":"BTCUSD"

编辑:

感谢 Wain 在下面的评论,使用 RKObjectMapping 足以让 KVC 验证工作。验证方法由 RestKit 自动调用。

到目前为止,我的代码如下所示:

RKObjectMapping *defaultMapping = [RKObjectMapping mappingForClass:class];

NSDictionary *attributeMappings = [query objectForKey:@"attributeMappings"];
[defaultMapping addAttributeMappingsFromDictionary:attributeMappings];

RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:dynamicMapping method:RKRequestMethodFromString(@"GET") pathPattern:@"/api/v1/markets" keyPath:@"" statusCodes:[NSIndexSet indexSetWithIndex:RKStatusCodeClassSuccessful]];
RKObjectManager *manager = [RKObjectManager managerWithBaseURL:url];
[manager addResponseDescriptor:responseDescriptor];

我添加了我认为验证NSObject 所必需的内容。

- (BOOL)validateCurrencyConversionID:(id *)ioValue error:(NSError **)outError
{
    if ([(NSString*)*ioValue length] == 0)
    {
        *outError = [NSError errorWithDomain:RKErrorDomain code:100 userInfo:@{@"description":@"Empty string"}];
        return NO;
    }
    else if ([((NSString*)*ioValue) rangeOfString:@"USD"].location == NSNotFound)
    {
        *outError = [NSError errorWithDomain:RKErrorDomain code:101 userInfo:@{@"description":@"Doesn't contain USD"}];
        return NO;
    }
    return YES;
}

【问题讨论】:

    标签: ios objective-c json restkit


    【解决方案1】:

    不要使用这种方法,因为您无法对数组进行适当的索引,因此您正在处理一个您期望字符串的数组。

    相反,允许为每个项目运行映射,然后使用 KVC validation 中止您不需要的项目的映射。

    【讨论】:

    • 嗨,你能评论一下我应该如何修复上面编辑过的代码吗?我觉得我还没有提供正确的映射。
    • 您不需要动态映射。您的 KVC 验证是否有效并拒绝不需要的项目?您尚未显示对 id 的验证。
    • 谢谢!我的代码越来越大,所以我不小心忘记了这段代码的属性映射。再次感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-14
    • 1970-01-01
    • 2012-08-24
    • 2012-12-22
    • 1970-01-01
    • 1970-01-01
    • 2018-05-28
    相关资源
    最近更新 更多