地幔 - 映射嵌套数据结构

时间:2015-05-29 06:36:44

标签: ios json

我有一个稍微复杂的嵌套JSON对象,我需要映射到Objective-C类。我认为我需要做的是在映射时跳过JSON中的级别。这就是我的意思:

我想映射以下JSON字典:

        def generateRecommendation(avroCustomer):
           print "=========================Generate Recommend========================="
           from pyspark import SparkContext,SparkConf
           from pyspark.sql import SQLContext

           print(type(avroCustomer))
           newAvroCustomer = avroCustomer.collect()
           for x in newAvroCustomer:
              print "===Query DB==="
              CustomerPurchaseHistorySingle=sqlContext.sql("SELECT * FROM CustomerPurchaseHistoryAllRec WHERE CustomerId=%s" % x)
              CustomerPurchaseHistorySingle.show()
              print(type(CustomerPurchaseHistorySingle))
              print(type(CustomerPurchaseHistoryAllRec))


           print "=======================Generated Recommend!========================"

NSDictionary *JSONDictionary = @{
         @"status" : @"PASSWORD_EXPIRED",
         @"_embedded" : @{
                 @"user" : @{
                         @"id" : @"00ub0oNGTSWTBKOLGLNR",
                         @"profile" : @{
                                 @"login" : @"isaac@example.org",
                                 @"firstName" : @"Isaac",
                                 @"lastName" : @"Brock",
                                 @"locale" : @"en_US",
                                 @"timeZone" : @"America/Los_Angeles"
                                 }
                         }
                 }
         };

正如您所看到的,我没有为“_embeded”创建对象。我正在跳过它并将用户映射到User对象。

这可以实现吗?如果是这样怎么样?

我在实现中尝试了这个但是没有用:

@interface Authentication : MTLModel <MTLJSONSerializing>
@property (strong, nonatomic) NSDate* expiresAt;
@property (strong, nonatomic) NSString* status;
@property (strong, nonatomic) NSString* relayState;
@property (strong, nonatomic) NSString* sessionToken;
@property (strong, nonatomic) NSString* stateToken;

//Embeded Resources
@property (strong, nonatomic) User* user;
@end

1 个答案:

答案 0 :(得分:2)

我曾经使用以下代码执行此操作:

+ (NSValueTransformer *)userJSONTransformer {
    return [MTLValueTransformer reversibleTransformerWithForwardBlock:^id(NSDictionary *userDict) {
        return [MTLJSONAdapter modelOfClass:[User class] fromJSONDictionary:userDict error:nil];
    } reverseBlock:^id(User *user) {
        return [MTLJSONAdapter JSONDictionaryFromModel:user];
    }];
}

同样在+JSONKeyPathsByPropertyKey我认为它应该是@"user" : @"_embeded.user"