2016-01-31 38 views
2

我在JSON正文中接收請求的多個緯度和經度鍵。使用地幔將多個按鍵組合成單個屬性

{ 
    ... 
    latitude: "28.4949762000", 
    longitude: "77.0895421000" 
} 

我想將它們合併成一個單一CLLocation財產而將其轉化爲我的JSON模式:

#import <Mantle/Mantle.h> 
@import CoreLocation; 

@interface Location : MTLModel <MTLJSONSerializing> 

@property (nonatomic, readonly) float latitude; 
@property (nonatomic, readonly) float longitude;  //These are the current keys 

@property (nonatomic, readonly) CLLocation* location; //This is desired 

@end 

如何去實現一樣嗎?

回答

2

終於找到了答案here。這是一個非常巧妙的方式,我很驚訝地發現它沒有在文檔中被明確提及。

將多個鍵組合成單個對象的方法是使用+JSONKeyPathsByPropertyKey方法中的數組將映射目標屬性爲多個鍵。當你這樣做的時候,地幔將在他們自己的NSDictionary實例中提供多個密鑰。

+(NSDictionary *)JSONKeyPathsByPropertyKey 
{ 
    return @{ 
      ... 
      @"location": @[@"latitude", @"longitude"] 
      }; 
} 

如果target屬性是NSDictionary,那麼就設置好了。否則,您需要在+JSONTransformerForKey+propertyJSONTransformer方法中指定轉換。

+(NSValueTransformer*)locationJSONTransformer 
{ 
    return [MTLValueTransformer transformerUsingForwardBlock:^CLLocation*(NSDictionary* value, BOOL *success, NSError *__autoreleasing *error) { 

     NSString *latitude = value[@"latitude"]; 
     NSString *longitude = value[@"longitude"]; 

     if ([latitude isKindOfClass:[NSString class]] && [longitude isKindOfClass:[NSString class]]) 
     { 
      return [[CLLocation alloc] initWithLatitude:[latitude floatValue] longitude:[longitude floatValue]]; 
     } 
     else 
     { 
      return nil; 
     } 

    } reverseBlock:^NSDictionary*(CLLocation* value, BOOL *success, NSError *__autoreleasing *error) { 

     return @{@"latitude": value ? [NSString stringWithFormat:@"%f", value.coordinate.latitude] : [NSNull null], 
       @"longitude": value ? [NSString stringWithFormat:@"%f", value.coordinate.longitude]: [NSNull null]}; 
    }]; 
} 
+1

它在[CHANGELOG]提及(https://github.com/Mantle/Mantle/blob/master/CHANGELOG.md#mapping-multiple-json-fields-to-a-single-property)但可能值得在README中找到一席之地! –

相關問題