如何使用RestKit映射JSON数组

5

我有一个类似以下格式的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,很有趣。 - erran
2
发现了一个 JSON 验证器 http://jsonlint.com/,看起来这是一个有效的格式。 :O - erran
我还没有找到解决方法。幸运的是,我也控制着我的服务器,并修改了服务器以添加顶级键。 - Paul Cezanne
2个回答

1

使用

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

您应该查看 Restkit 对象映射文档中的 "不使用 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];

嗯,看起来当前的RK版本没有这个“-addObjectMapping”方法。现在我们该怎么办?有更新吗? - boog
这个回答有5年的历史了...现在不在iOS上开发了 :C - clopez

0

对我来说,解决方案是:

添加此响应描述符,使用数组内部的对象

[manager addResponseDescriptor:[ObjectInsideTheArray getResponseDescriptor]];

在成功的响应中

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接