0

我正在使用 RESTKit 执行 GET 请求,我需要帮助映射 JSON 响应。这是我需要映射的响应:

{"limit_hit":false,"providers":
    [{"id":876553,
    "name":"Cooper, Bradley N, DDS",
    "specialty_groups":["Other Provider"],
    "tags":[],
    "has_comments":false,
    "number_of_comments":0,
    "locations":
        [{"address":"1234 Rifle Range Road, El Cerrito, CA, 94530",
        "providers_at_address_count":1,
        "client_product_count":0,
        "non_client_product_count":2,
        "address_lines":["1234 Rifle Range Road, El Cerrito, CA, 94530"],
        "address_id":234578,
        "specialty_groups":
            [{"specialty_group":"Other Provider"}],
        "provider_types":
            [{"provider_type":"Other Provider"}]},

        {"address":"7501 Mission Rd, Shawnee Mission, KS, 66208",
        "providers_at_address_count":2,
        "client_product_count":0,
        "non_client_product_count":2,
        "address_lines":["7654 Main S, El Cerrito, CA, 94530"],
        "address_id":654432,
        "specialty_groups":
            [{"specialty_group":"Other Provider"}],
        "provider_types":
            [{"provider_type":"Other Provider"}]
        }]
    }]
}

我希望能够映射两个地址,但我不知道如何。我目前所能做的就是映射 id、name、has_comments 和 number_of_comments(我正在使用“providers”的键路径)。这是我当前的映射提供者:

+ (RKMapping *)searchMapping
{
    RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[ProviderSearch class]];
    [mapping addAttributeMappingsFromDictionary:@{
     @"id": @"doctorID",
     @"name": @"name",
     }];
    return mapping;
}

我到底做错了什么,我该如何解决?

4

2 回答 2

1

创建另一个方法来返回映射locations,然后将该映射关联到这个原始映射。像这样:

// ProviderLocation.m
+ (RKObjectMapping *)objectMapping
{
    RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[ProviderLocation class]];
    [mapping addAttributeMappingsFromDictionary:@{
     @"address": @"address",
     ...
     }];
    return mapping;
}

关系:

+ (RKObjectMapping *)searchMapping
{
    RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[ProviderSearch class]];
    [mapping addAttributeMappingsFromDictionary:@{
     @"id": @"doctorID",
     @"name": @"name",
     }];

    RKObjectMapping *locationsMapping = [ProviderLocation objectMapping];
    [mapping addPropertyMapping:
        [RKRelationshipMapping relationshipMappingFromKeyPath:@"locations" toKeyPath:@"locations" withMapping:locationsMapping]];

    return mapping;
}

只要记住在ProviderLocation.hnamed中创建一个 NSArray 属性locations

于 2013-08-06T17:21:25.367 回答
0

我以前从未使用过 RKObjectMapping,但是您拥有的“位置”有一个字典对象数组。所以你需要一个

NSArray loc = [myJson objectForKey:@"locations"];
for(NSDictionary *dict in loc){
    //here each dict obj will have your "address",  "providers_at_address_count" and etc... so if you want to access any of them you can call...
    NSString *addr = [dict objectForKey:@"address"];
 }

现在以某种方式将其转换为您使用 RXObjectMapping 所做的事情,您是金子 =P

于 2013-08-06T17:23:24.193 回答