Question

I'm trying to conver this JSON to a model:

  [
    {
        "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"
    }
]

This is my class:

@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

Thought if I named the vars exactly the same it wouldn't be necessary to implement JSONKeyPath but I did.

And this is my method to convert:

-(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);
}
}

where model is my classname and responseObject is just a id object I filled with AFNetworking.

I'm always getting this error:

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
Was it helpful?

Solution

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];
//...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top