0

我正在尝试使用 githubs mantle 获取 JSON 文件的子节点。这是我尝试过的:

JSON

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

国家信息.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

国家信息网

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

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

运行我的应用程序时出现错误:

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

2 回答 2

0

如果要将人口数量存储在populationInCities数组中,则需要一个自定义转换器:

+ (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];
    }];
}
于 2014-12-26T19:30:49.180 回答
0

令人尴尬,但它只是使用 .-notation 工作。

例如 popukationInCities.hamburg

于 2015-01-11T21:38:15.863 回答