【问题标题】:How to map a JSON array with RestKit如何使用 RestKit 映射 JSON 数组
【发布时间】:2012-06-12 06:19:50
【问题描述】:

我有这种格式的json字符串:

[{"image":"/0001.jpg","link":"/index.php"},
{"image":"/0001.jpg","link":"/index.php"}]

它在顶层没有键。

[mapping mapKeyPath:@"image" toAttribute:@"image"];

这样的映射不起作用,它给了我错误:

restkit.object_mapping:RKObjectMapper.m:81 Adding mapping error: Could not find an object mapping for keyPath: ''

如何映射这种类型的json?

【问题讨论】:

  • 那是 JSON 字典的正确格式吗,我认为在顶层添加键是正式的。我猜这不是你要编辑的 json,很有趣。
  • 我还没有找到办法。幸运的是,我还控制了我的服务器并修改了服务器以添加顶级密钥。

标签: ios json restkit


【解决方案1】:

使用

[[RKObjectManager sharedManager].mappingProvider addObjectMapping:myObject];

您应该查看 Restkit 对象映射文档中的“Mapping without KVC”部分。

这是文档中的一个示例:

[
    { "title": "RestKit Object Mapping Intro",
      "body": "This article details how to use RestKit object mapping...",
      "author": {
          "name": "Blake Watters",
          "email": "blake@restkit.org"
      },
      "publication_date": "7/4/2011"
    }
]

然后你像这样映射:

// Our familiar articlesMapping from earlier
RKObjectMapping* articleMapping = [RKObjectMapping mappingForClass:[Article class]];
[articleMapping mapKeyPath:@"title" toAttribute:@"title"];
[articleMapping mapKeyPath:@"body" toAttribute:@"body"];
[articleMapping mapKeyPath:@"author" toAttribute:@"author"];
[articleMapping mapKeyPath:@"publication_date" toAttribute:@"publicationDate"];

[[RKObjectManager sharedManager].mappingProvider addObjectMapping:articleMapping];

【讨论】:

  • hmm,看起来列表当前的 RK 版本没有这个-addObjectMapping 方法。我们现在能做什么?有更新吗?
  • 这个答案有 5 年......现在不在 iOS 上开发:C
【解决方案2】:

对我来说,解决方案是:

添加这个响应描述符,使用de数组里面的对象

[manager addResponseDescriptor:[ObjectInsideTheArray getResponseDescriptor]];

并在成功响应中

NSArray *response = (NSArray *)[mappingResult array]; //而不是firstObject

【讨论】:

    猜你喜欢
    • 2012-06-24
    • 2015-09-08
    • 2015-05-29
    • 2013-08-14
    • 2013-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多