2014-11-20 31 views
0

我試圖獲取JSON文件中使用githubs地幔的子節點。 這是我的嘗試:使用github-mantle獲取JSON子樹

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 

ÇountryInfo.m

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

回答

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]; 
    }]; 
} 
0

尷尬,但它是模擬使用.-符號工作。

例如 popukationIncities.hamburg