如何使用RestKit映射JSON数组

时间:2012-06-08 07:22:21

标签: ios json restkit

我有像这种格式的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?

2 个答案:

答案 0 :(得分:1)

使用

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

你应该检查" Mapping without KVC"关于Restkit对象映射文档的部分。

以下是文档中的示例:

[
    { "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];

答案 1 :(得分:0)

对我而言,解决方案是:

添加此响应描述符,使用de array中的对象

[manager addResponseDescriptor:[ObjectInsideTheArray getResponseDescriptor]];

并在成功回复中

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