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

标签 ios objective-c restkit

我希望使用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/

相关文章:

ios - NSDateFormatter 问题 - 获取错误的日期

ios - Objective-C 中的委托(delegate)方法和 Swift 中的 View Controller 。如何调用协议(protocol)? - iOS

ios - 点击时 UICollectionView 单元格更改背景

ios - UIAlertView 输入提示

objective-c - RestKit .2 将图像发布到 Web 服务 - 空实体错误

ios - Restkit v0.20动态映射到NSDictionary

ios - 请求 addValue : forHTTPHeaderField gets the token but does not sends it to server in RestKit

java - 带有 JDBC 的 Gluon 示例项目在 iOS 设备上不起作用

ios - 可变运算符的左侧不可变 '..<' 返回不可变值

iOS 向 Web 服务器发送命令