2

我正在尝试将此 JSON 转换为模型:

  [
    {
        "status": "Top-up done",
        "amount": "25.00",
        "amount_ex_vat": "20.66",
        "executed_on": "2014-07-28 20:21:33",
        "method": "Bancontact/Mister Cash",
        "payment_received_on": "2014-07-28 20:21:29"
    },
    {
        "status": "Top-up done",
        "amount": "15.00",
        "amount_ex_vat": "12.40",
        "executed_on": "2014-05-26 19:41:36",
        "method": "PayPal",
        "payment_received_on": "2014-05-26 19:41:31"
    },
    {
        "status": "Top-up done",
        "amount": "10.00",
        "amount_ex_vat": "8.26",
        "executed_on": "2014-02-26 20:43:39",
        "method": "PayPal",
        "payment_received_on": "2014-02-26 20:43:35"
    },
    {
        "status": "Top-up done",
        "amount": "15.00",
        "amount_ex_vat": "12.40",
        "executed_on": "2014-01-18 12:43:09",
        "method": "PayPal",
        "payment_received_on": "2014-01-18 12:43:06"
    }
]

这是我的课:

@interface TopupHistory : MTLModel 
@property (strong, nonatomic) NSString * amount;
@property (strong, nonatomic) NSString * executed_on;
@property (strong, nonatomic) NSString * method;
@end

@implementation TopupHistory

(NSDictionary *)JSONKeyPathsByPropertyKey { return @{ @"amount": @"amount", @"executed_on": @"executed_on", @"method": @"method", }; } @end

认为如果我将变量命名为完全相同,则不需要实现 JSONKeyPath,但我做到了。

这是我的转换方法:

-(void) convertFrom:(id) responseObject toModel:(Class) model resultBlock: (NetworkBlock)resultBlock
{
NSError * didFail;
id result = [MTLJSONAdapter modelOfClass:model fromJSONDictionary:responseObject error:&didFail];
if (!didFail) {
resultBlock(result,nil);
}
else
{
NSLog(@"Couldn't convert app infos JSON to model: %@", didFail);
resultBlock(nil,didFail);
}
}

其中 model 是我的类名,responseObject 只是我用 AFNetworking 填充的 id 对象。

我总是收到这个错误:

Domain=MTLJSONAdapterErrorDomain Code=3 "Missing JSON dictionary" UserInfo=0x913a690 {NSLocalizedFailureReason=TopupHistory could not be created because an invalid JSON dictionary was provided: __NSCFArray, NSLocalizedDescription=Missing JSON dictionary}
2014-07-29 13:11:55.780 test Info[10953:60b] Missing JSON dictionary
4

1 回答 1

2

You response is an array of dictionaries, so you should use the MTLJSONAdapter method modelsOfClass:fromJSONArray:error: to convert them to an array of Mantle models.

Your code should be changed as below:

-(void) convertFrom:(id) responseObject toModel:(Class) model resultBlock: (NetworkBlock)resultBlock
{
NSError * didFail;
id result = [MTLJSONAdapter modelsOfClass:model fromJSONArray:responseObject error:&didFail];
//...
于 2014-07-29T12:28:25.267 回答