我有一个 CoreData 支持的联系人对象,它与电子邮件和电话号码实体具有一对多的关系。这里提到的所有对象都是 NSManagedObjects。
phone_number 和 email 实体都只有一个属性,即分别代表 phone_number 和 email 的 NSString*。
目前,当我序列化对象时,我得到类似
{contacts:
[{"name":"person1",
"emails":[{"email":"email1@email.com"}, {"email":"email2@email.com"}],
"phone_numbers":[{"number":"1111111111"}, {"number":"2222222222"}]},
{"name":"person2",
"emails":[{"email":"email1@email.com"}, {"email":"email2@email.com"}],
"phone_numbers":[{"number":"3333333333"}, {"number":"4444444444"}]}]
}
我想序列化成这样的东西
{contacts:
[{"name":"person1",
"emails":["email1@email.com","email2@email.com"],
"phone_numbers":["1111111111", "2222222222"]},
{"name":"person2",
"emails":["email1@email.com", "email2@email.com"],
"phone_numbers":["3333333333", "4444444444"]}]
}
注意“电子邮件”和“电话号码”列表只是一个字符串列表,没有每个电话号码/电子邮件的关联键
我当前的映射代码是(电话号码映射代码与电子邮件映射代码完全相同)
@implementation Email
@dynamic email;
@dynamic contact;
+ (void)emailRKObjectMapping {
RKManagedObjectMapping* emailMapping = [RKManagedObjectMapping mappingForEntityWithName:@"Email" inManagedObjectStore:[RKObjectManager sharedManager].objectStore];
[emailMapping mapKeyPath:@"email" toAttribute:@"email"];
[[RKObjectManager sharedManager].mappingProvider addObjectMapping:emailMapping];
//Serialization mapping for Contact class
[[RKObjectManager sharedManager].mappingProvider setSerializationMapping":[emailMapping inverseMapping] forClass:[Email class]];
}
@end
具有指向电子邮件/电话号码的关系的联系人映射代码
@implementation Contact
...
@dynamic emails;
@dynamic phoneNumbers;
...
+ (void)contactRKObjectMapping {
RKManagedObjectMapping* contactMapping = [RKManagedObjectMapping mappingForEntityWithName:@"Contact" inManagedObjectStore:[RKObjectManager sharedManager].objectStore];
...
...
[[RKObjectManager sharedManager].mappingProvider addObjectMapping:contactMapping];
//Serialization mapping for Contact class
RKManagedObjectMapping* contactSerializationMapping = [contactMapping copy];
[contactSerializationMapping mapKeyPath:@"emails" toRelationship:@"emails" withMapping:[[RKObjectManager sharedManager].mappingProvider objectMappingForClass:[Email class]]];
[contactSerializationMapping mapKeyPath:@"phone_numbers" toRelationship:@"phoneNumbers" withMapping:[[RKObjectManager sharedManager].mappingProvider objectMappingForClass:[PhoneNumber class]]];
[[RKObjectManager sharedManager].mappingProvider setSerializationMapping:[contactSerializationMapping inverseMapping] forClass:[Contact class]];
}
对我来说,必须为电子邮件和电话号码数组中的每个电话号码和电子邮件发送密钥“电话号码”或“电子邮件”似乎很愚蠢。我只是想要一种简单的方法来用一个键序列化字符串数组。
谢谢你的帮助!