gpt4 book ai didi

objective-c - RestKit RKObjectMapping 嵌套 json

转载 作者:可可西里 更新时间:2023-11-01 03:31:25 24 4
gpt4 key购买 nike

如何使用 RestKit RKObjectMapping 映射下面嵌套的 json?我只需要映射“数据”。我当前的下面代码返回 (null) - 谢谢!

{

"sucess": true,
"error": {
"code": "",
"message": ""
},
"data": [
{
"id": 1,
"name": "Salad",
"description": "Salad Desc",
"category_id": 1
},
{
"id": 2,
"name": "Soup",
"description": "Soup Desc",
"category_id": 1
},
{
"id": 3,
"name": "Wrap",
"description": "Wrap Desc",
"category_id": 1
},
{
"id": 4,
"name": "Appetizers",
"description": "Appetizers Desc",
"category_id": 1
}
]

}

@interface Subcategory : NSObject    
@property (nonatomic, retain) NSNumber *subcategoryID;
@property (nonatomic, retain) NSNumber *categoryID;
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSString *description;
@property (nonatomic, retain) NSString *thumbnail;
@property (nonatomic, retain) NSArray *data;

View Controller

RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[Subcategory class]];

RKObjectMapping* dataMapping = [RKObjectMapping mappingForClass:[Subcategory class]];
[dataMapping mapKeyPath:@"id" toAttribute:@"subcategoryID"];
[dataMapping mapKeyPath:@"category_id" toAttribute:@"categoryID"];
[dataMapping mapAttributes:@"name", @"description", nil];

[mapping mapKeyPath:@"data" toRelationship:@"data" withMapping:dataMapping];

[[RKObjectManager sharedManager] loadObjectsAtResourcePath:[NSString stringWith

最佳答案

您缺少 rootKeyPath 并且还在提供程序中设置了映射:

RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[Subcategory class]];    
RKObjectMapping* dataMapping = [RKObjectMapping mappingForClass:[Subcategory class]];
[dataMapping mapKeyPath:@"id" toAttribute:@"subcategoryID"];
[dataMapping mapKeyPath:@"category_id" toAttribute:@"categoryID"];
[dataMapping mapAttributes:@"name", @"description", nil];
dataMapping.rootKeyPath = @"data"; //this is what you were missing
//get your mapping provider (i'm not sure if you already have on declared)
[mappingProvider setObjectMapping:dataMapping forResourcePathPattern:@"/somepath/toservice/"];
[[RKObjectManager sharedManager] loadObjectsAtResourcePath:@"/somepath/toservice/"];

这里有更多信息可以回答您有关获取其他元素(例如“错误”)的问题:

- (void)objectLoader:(RKObjectLoader *)objectLoader didFailWithError:(NSError *)error {
NSError *parseError = nil;
id response = [objectLoader.response parsedBody:&parseError];
DLog(@"response %@", response);
if (!parseError) {
NSString *errorMessage = [[response valueForKey:@"error"] valueForKey:@"message"];
//do something with it
}
}

关于objective-c - RestKit RKObjectMapping 嵌套 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10167486/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com