get subTree of JSON using github-mantle

229 views Asked by At

I'm trying to get the subnodes of a JSON file usning githubs mantle. This is what I tried:

JSON

"countries": {
        "name": "germany",
        "population": "80620000000",
        "populationInCities": {
            "Hamburg": 1799000,
            "Berlin": 3502000,
            "Munich": 1378000
        }
    }

CountryInfo.h

#import <Mantle/Mantle.h>


@interface CountryInfo : MTLModel <MTLJSONSerializing>

@property (nonatomic, readonly, copy) NSString *collectionName;
@property (nonatomic, readonly, assign) NSUInteger cPopulation;
@property (nonatomic, readonly, copy) NSArray *populationInCities;

@end

CountryInfo.m

+ (NSDictionary *)JSONKeyPathsByPropertyKey {
        return @{ @"cName": @"name",
                  @"cPopulation": @"population",
                  @"populationInCities": [NSSet setWithArray:@[ @"Hamburg", @"Hamburg", @"Hamburg"]]
                  };
    }

+ (NSValueTransformer *)populationInCitiesJSONTransformer {
    return [NSValueTransformer mtl_JSONArrayTransformerWithModelClass:CountryInfo.class];
}

I'm getting an error when I run my APP:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'populationInCities must either map to a JSON key path or NSNull, got: {
    populationInCities =     (
        Hamburg,
        Berlin,
        Munich
    );
}.'
2

There are 2 answers

0
Maxim Pavlov On

If you want to store population numbers in populationInCities array, you need a custom transformer:

+ (NSDictionary *)JSONKeyPathsByPropertyKey {
    return @{@"collectionName": @"name",
             @"cPopulation": @"population"};// 'populationInCities' names in JSON and model are the same, so no need to include here.
}

+ (NSValueTransformer *)populationInCitiesJSONTransformer {
    return [MTLValueTransformer transformerWithBlock:^(NSDictionary *dict) {
        return [dict allValues];
    }];
}
0
Michael On

Embarrassing, but it was simly working using .-notation.

e.g. popukationInCities.hamburg