草庐IT

ios - RestKit 嵌套同类型对象 -- JSON 集合错误

coder 2024-01-12 原文

我正在使用 RestKit 提取可能包含 child 评论的评论(这些 child 可能有 child 等)。

我能够毫无问题地深入提取 0 条评论。对于每个深度为 0 的评论,我都有一组评论对象。每个父评论都填充了正确数量的子评论,但是子评论中的所有属性都是零(只有深度为 0 的父评论填充了真实数据)。 RestKit 给我警告:

W restkit.object_mapping:RKMappingOperation.m:645 WARNING: Detected a relationship mapping for a collection containing another collection. This is probably not what you want. Consider using a KVC collection operator (such as @unionOfArrays) to flatten your mappable collection.
W restkit.object_mapping:RKMappingOperation.m:646 Key path 'comments.comments' yielded collection containing another collection rather than a collection of objects:

此外,对于我尝试映射到子项中的每个属性,我都会收到此消息(按属性类型更改)

E restkit.object_mapping:RKMappingOperation.m:440 Failed transformation of value at keyPath 'vote_count' to representation of type 'NSNumber': Error Domain=org.restkit.RKValueTransformers.ErrorDomain Code=3002 "Failed transformation of value '( )' to NSNumber: none of the 2 value transformers consulted were successful." UserInfo=0x8e68280 {detailedErrors=( "Error Domain=org.restkit.RKValueTransformers.ErrorDomain Code=3002 \"The given value is not already an instance of 'NSNumber'\" UserInfo=0x8e681e0 {NSLocalizedDescription=The given value is not already an instance of 'NSNumber'}", "Error Domain=org.restkit.RKValueTransformers.ErrorDomain Code=3000 \"Expected an inputValue of type NSNull, but got a __NSArrayI.\" UserInfo=0x8e68210 {NSLocalizedDescription=Expected an inputValue of type NSNull, but got a __NSArrayI.}" ), NSLocalizedDescription=Failed transformation of value '( )' to NSNumber: none of the 2 value transformers consulted were successful.}

尽管有警告,但我相信这就是我想要的——但它在映射子对象方面遇到了困难。它提示说它在需要属性类型时“得到了一个 NSArray”,所以我假设我的属性映射不正确。

这是我的映射:

+ (RKMapping *) dnCommentMapping {
RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[DNComment class]];
[mapping addAttributeMappingsFromDictionary:@{
                                              @"id": @"commentId",
                                              @"body": @"body",
                                              @"body_html": @"bodyHTML",
                                              @"created_at": @"createdAt",
                                              @"depth": @"depth",
                                              @"vote_count": @"voteCount",
                                              @"user_id": @"userID",
                                              @"user_display_name": @"userDisplayName",
                                              }];
[mapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"comments.comments"
                                                                        toKeyPath:@"comments"
                                                                      withMapping:mapping]];

return mapping;
}

这是我的对象

@interface DNComment : NSObject
@property (nonatomic, assign) NSInteger commentId;
@property (nonatomic, copy) NSString *body;
@property (nonatomic, copy) NSString *bodyHTML;
@property (nonatomic, copy) NSDate *created_at;
@property (nonatomic, assign) NSInteger depth;
@property (nonatomic, assign) NSInteger voteCount;
@property (nonatomic, copy) NSDate *createdAt;
@property (nonatomic, assign) NSInteger userID;
@property (nonatomic, copy) NSString *userDisplayName;
@property (nonatomic, strong) NSArray *comments;
@end

我的 RKResponseDescriptor

RKMapping *mapping = [DNAMappingProvidor dnCommentMapping];
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:mapping
                                                                                        method:RKRequestMethodGET
                                                                                   pathPattern:/api/v1/stories/1
                                                                                       keyPath:@"story.comments"
                                                                                   statusCodes:statusCodeSet];

您可以在图像中看到填充了深度 0 评论,它创建了正确数量的子项(并且他们的子项计数是正确的),但它们没有被填充。

这是我尝试映射的 JSON 示例

{
"story": {
"badge": "discussion",
"comment": "THE STORY",
"comments": [
  {
    "body": "THIS IS MY COMMENT - I GET MAPPED FINE",
    "body_html": "<p>THIS IS MY COMMENT - I GET MAPPED FINE</p>\n",
    "comments": [
      {
        "body": "THIS IS MY CHILD RESPONSE - NONE OF MY PROPERTIES GET SET",
        "body_html": "<p>THIS IS MY CHILD RESPONSE - NONE OF MY PROPERTIES GET SET</p>\n",
        "comments": [
          {
            "body": "THIS IS MY CHILD'S CHILD RESPONSE - NONE OF MY PROPERTIES GET SET",
            "body_html": "<p>THIS IS MY CHILD'S CHILD RESPONSE - NONE OF MY PROPERTIES GET SET </p>\n",
            "comments": [

            ],
            "created_at": "2014-02-17T21:07:13Z",
            "depth": 2,
            "id": 41665,
            "url": "https://www.www.com",
            "user_display_name": "A M.",
            "user_id": 201,
            "user_job": "Job Title",
            "user_portrait_url": "image.png",
            "user_url": "user.com",
            "vote_count": 1
          }
        ],
        "created_at": "2014-02-17T20:50:05Z",
        "depth": 1,
        "id": 41655,
        "url": "https://www.www.com",
        "user_display_name": "M K.",
        "user_id": 3517,
        "user_job": "Job Title",
        "user_portrait_url": "image.png",
        "user_url": "user.com",
        "vote_count": 2
      }
    ],
    "created_at": "2014-02-17T20:14:47Z",
    "depth": 0,
    "id": 41649,
    "url": "www.www.com",
    "user_display_name": "A M.",
    "user_id": 201,
    "user_job": "Job Title",
    "user_portrait_url": "image.com",
    "user_url": "user.com",
    "vote_count": 32
  },

谢谢

最佳答案

看起来你的问题只是这一部分:

[mapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"comments.comments"

因为关键路径应该只是@"comments"。您无需深入了解结构,RestKit 会在导航应用映射的 JSON 时为您完成这项工作。

关于ios - RestKit 嵌套同类型对象 -- JSON 集合错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22240320/

有关ios - RestKit 嵌套同类型对象 -- JSON 集合错误的更多相关文章

  1. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  2. ruby-on-rails - 按天对 Mongoid 对象进行分组 - 2

    在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev

  3. ruby-on-rails - Rails 编辑表单不显示嵌套项 - 2

    我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib

  4. ruby - 将散列转换为嵌套散列 - 2

    这道题是thisquestion的逆题.给定一个散列,每个键都有一个数组,例如{[:a,:b,:c]=>1,[:a,:b,:d]=>2,[:a,:e]=>3,[:f]=>4,}将其转换为嵌套哈希的最佳方法是什么{:a=>{:b=>{:c=>1,:d=>2},:e=>3,},:f=>4,} 最佳答案 这是一个迭代的解决方案,递归的解决方案留给读者作为练习:defconvert(h={})ret={}h.eachdo|k,v|node=retk[0..-2].each{|x|node[x]||={};node=node[x]}node[

  5. ruby-on-rails - 如何验证非模型(甚至非对象)字段 - 2

    我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss

  6. Ruby 写入和读取对象到文件 - 2

    好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信

  7. ruby-on-rails - Rails HTML 请求渲染 JSON - 2

    在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这

  8. ruby - Infinity 和 NaN 的类型是什么? - 2

    我可以得到Infinity和NaNn=9.0/0#=>Infinityn.class#=>Floatm=0/0.0#=>NaNm.class#=>Float但是当我想直接访问Infinity或NaN时:Infinity#=>uninitializedconstantInfinity(NameError)NaN#=>uninitializedconstantNaN(NameError)什么是Infinity和NaN?它们是对象、关键字还是其他东西? 最佳答案 您看到打印为Infinity和NaN的只是Float类的两个特殊实例的字符串

  9. ruby - 检查方法参数的类型 - 2

    我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)

  10. ruby-on-rails - 如果 Object::try 被发送到一个 nil 对象,为什么它会起作用? - 2

    如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象

随机推荐