1

我很难让序列化适用于对象可能包含自身其他实例的对象。

例如对象: Person NSString* name Person* mother 这个 JSON 可能看起来像:{

"person": [

           {

            "name": "Blake Watters",

            "mother": {

                "name": "Jane Doe",

                "mother": {

                    "name":"Jane Smith",

                    "age":65

                }

            }

           }

        ]

}

我创建映射: RKObjectMapping* personMapping = [RKObjectMapping mappingForClass:[Person class] ];

[personMapping mapAttributes:@"name", nil];

[personMapping mapKeyPath:@"mother" 
           toRelationship:@"mother" 
              withMapping:personMapping];

如果我对此执行逆映射以便可以序列化对象,我会得到一个递归映射错误,因为它不断添加映射。

我能找到的唯一答案是在关系上设置“序列化:否”。这允许它逆向然后序列化,但是序列化当然是缺少母对象。

有没有解决的办法?反转后,我可以手动将此序列化添加回对象吗?

编辑:

看起来之后将其重新添加可能是实现此目的的方法,因为以下代码似乎有效。虽然感觉必须有更好的方法。

// Map name
RKObjectMapping* nameMapping = [RKObjectMapping mappingForClass:[Name class]];
[nameMapping mapAttributes:@"first",@"last", nil];

// Map person
RKObjectMapping* personMapping = [RKObjectMapping mappingForClass:[Person class] ];
[personMapping mapAttributes:@"age", nil];
[personMapping mapKeyPath:@"name" toRelationship:@"name" withMapping:nameMapping];

// Don't serialize mother
[personMapping mapKeyPath:@"mother" toRelationship:@"mother" withMapping:personMapping serialize:NO];

// Connect our mapping to RestKit's mapping provider
[[RKObjectManager sharedManager].mappingProvider setMapping:personMapping forKeyPath:@"person"];

// invert the mapping
RKObjectMapping* personSerialization = [personMapping inverseMapping];
RKObjectMapping* mapping = [[RKObjectManager sharedManager].mappingProvider 
                            serializationMappingForClass:[Person class]];
// Since mother wasn't serialized, add its relationship back in
[personSerialization mapKeyPath:@"mother" 
                 toRelationship:@"mother" 
                    withMapping:personSerialization];    
[[RKObjectManager sharedManager].mappingProvider setSerializationMapping:personSerialization 
                                                                forClass:[Person class]];

谢谢,亚当

4

0 回答 0