gpt4 book ai didi

ios - 将对象数组映射到父对象数组中

转载 作者:行者123 更新时间:2023-11-29 02:45:46 26 4
gpt4 key购买 nike

我在通过 RestKit 的映射功能从 JSON 映射父对象(请求)数组中的对象数组(评论)时遇到问题。

我所有的数据都正确返回,但由于某种原因,评论对象从未被填充!

请参阅下面的代码:

请求.json:

{
"data": {
"priorityRequests": [
{
"id": 123456,
"title": "Request 1",
"comments": [
{
"author": "John Smith",
"content": "This is a comment"
}, {
"author": "Jane Smith",
"content": "This is another comment"
}
]
}, {
"id": 654321,
"title": "Request 2",
"comments": [
{
"author": "John Smith",
"content": "This is a comment"
}, {
"author": "Jane Smith",
"content": "This is another comment"
}
]
}
]
}
}

评论.h/m

@interface Comment : NSObject

@property ( strong, nonatomic ) NSString *author;
@property ( strong, nonatomic ) NSString *content;

@end

@implementation Comment

@end

Request.h/m

@import "Request.h"

@interface Request : NSObject

@property ( strong, nonatomic ) NSString *id;
@property ( strong, nonatomic ) NSString *title;
@property ( strong, nonatomic ) Comment *comments;

@end

@implementation Request

@end

RequestManager.m 片段

RKObjectMapping *requestMapping = [ RKObjectMapping mappingForClass: [ Request class ] ];
[ requestMapping addAttributeMappingsFromDictionary:@{
@"id" : @"id",
@"title" : @"versionNumber"
}];

RKObjectMapping *commentMapping = [ RKObjectMapping mappingForClass: [ Comment class ] ];
[ commentMapping addAttributeMappingsFromDictionary:@{
@"title": @"title",
@"author": @"author"
}];

// Failed attempt 1:
[ requestMapping addPropertyMapping: [ RKRelationshipMapping
relationshipMappingFromKeyPath: @"comments"
toKeyPath: @"comments"
withMapping: commentMapping ]
];
// end

// Failed attempt 2:
RKRelationshipMapping* requests_comments = [ RKRelationshipMapping
relationshipMappingFromKeyPath: @"comments"
toKeyPath: @"comments"
withMapping: commentMapping
];

[ requestMapping addPropertyMapping: requests_comments ];
// end

RequestCommunicator.m 片段

NSDictionary *mappingsDictionary = @{ "data.priorityRequest" : requestMapping };

RKMapperOperation *mapper = [ [ RKMapperOperation alloc ]
initWithRepresentation: parsedData // parsed json as above
mappingsDictionary: mappingsDictionary
];

NSError *mappingError = nil;

BOOL isMapped = [ mapper execute: &mappingError ];

// If no errors, returned array of mapped objects
if (isMapped && !mappingError) {

// All data except for comments here
// _comments = (Comment *) nil
[ self.delegate receivedResponseObject: [ mapper mappingResult ].array ];

... etc.

最佳答案

我找到了这个问题的解决方案,虽然可能不是每个人都喜欢,但希望它可以帮助其他人走上正轨。

在我的 Requests NSObject 中,我将映射类型从“Comment”更改为“NSArray”:

- @property ( strong, nonatomic ) Comment *comments;
+ @property ( strong, nonatomic ) NSArray *comments;

关于ios - 将对象数组映射到父对象数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25155216/

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