gpt4 book ai didi

ios - RestKit - 将动态属性映射到键值对

转载 作者:行者123 更新时间:2023-11-29 01:46:41 25 4
gpt4 key购买 nike

我希望使用restkit 映射以下JSON。

"ObjectDetails":
[
{
"ObjectName":"Test1",
"Properties":
{
"PropertyName1":1,
"PropertyName3":2
}
},
{
"ObjectName":"Test2",
"Properties":
{
"PropertyName1":1,
"PropertyName2":"asdf"
}
},
{
"ObjectName":"Test3",
"Properties":
{
"PropertyName1":1,
"PropertyName6":3423,
"PropertyName7":"test",
"PropertyName3":2
}
}
]

对象

@interface ObjectDetail : NSObject
@property (nonatomic, strong) NSString *objectName;
//????
@end

映射

RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[ObjectDetail class]];
[mapping addAttributeMappingsFromDictionary:@{@"ObjectName":@"objectName"}];

RKResponseDescriptor *rd = [RKResponseDescriptor responseDescriptorWithMapping:mapping method:RKRequestMethodAny pathPattern:nil keyPath:@"ObjectDetails" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];

我的问题是“属性”具有动态属性。我还没有找到将属性映射到任何东西的方法。理想情况下,将属性映射到键/值字典会很好。我确实需要字段名称和值。

即。

@interface ObjectDetail : NSObject
@property (nonatomic, strong) NSString *objectName;
@property (nonatomic, strong) NSMutableDictionary *properties;
@end

有人知道这个问题的解决方案或者知道如何实现它吗?

更新:基于@Idali 解决方案,非常简单。如果您发现这有帮助,请务必给他们的答案点赞!

对象

@interface ObjectDetail : NSObject
@property (nonatomic, strong) NSString *objectName;
@property (nonatomic, strong) id *properties;
@end

映射

RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[ObjectDetail class]];
[mapping addAttributeMappingsFromDictionary:@{@"ObjectName":@"objectName", @"Properties": @"properties"}];

然后直接转换即可。

self.myDictionnay  = (NSDcitionnary*) objectDetail.properties;

最佳答案

您可以通过在 coredata 中将“properties”属性设置为 transformable 类型来解决它,并在您的 ObjectCalss 中将其声明为 id 并映射它。如果您创建 ManagedObject 子类,它将是:

@property (nonatomic, retain) id 属性;

要阅读内容,您可以转换它:........

NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
ObjectDetail* objectDetail =[fetchedObjects firstObject];
self.myDictionnay = (NSDcitionnary*) objectDetail.properties;
NSArray* keys = [self.myDictionnay allKeys];//检查是否存在任何 key

关于ios - RestKit - 将动态属性映射到键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31842920/

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