我很难映射一个特定案例 这与 here 完全相同
product:{
"id": 123,
"name": "Produce RestKit Sample Code",
"description": "We need more sample code!",
"tasks": [
{"name": "Identify samples to write", "assigned_user_id":1},
{"name": "Write the code", "assigned_user_id": 1},
{"name": "Push to Github", "assigned_user_id": 1},
{"name": "Update the mailing list", "assigned_user_id": 1}]
}
所以我为任务对象创建了映射。 我为与 NSSET 任务相关的产品对象创建了映射。
但现在每次解析新数据时,核心数据中的任务都是重复的。 (正常原因没有ID)
两种解决方案:
- 如果发现新任务,我可以删除当前产品的任务。
- 我可以使用产品 ID 创建任务 ID
我不知道如何实现这些解决方案。任何帮助都会很棒。
最佳答案
我不太确定你是如何映射这个任务对象的,但我通过以下方式用 JSON 字符串解析 NSData
:
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data
options:0
error:&error];
在那种情况下,我得到一个带有一个键“product”的 NSDictionary
,并且该键的对象是另一个字典。带有“tasks”键的 NSDictionary
的对象是一个包含四个 NSDictionary
对象的 NSArray
。
现在,该 JSON 摘录不是有效的 JSON,但我认为它只是更广泛的 JSON 文件的一片叶子。但出于测试目的,我们假设 JSON 文件如下:
{
"product" : {
"id": 123,
"name": "Produce RestKit Sample Code",
"description": "We need more sample code!",
"tasks": [
{"name": "Identify samples to write", "assigned_user_id": 1},
{"name": "Write the code", "assigned_user_id": 1},
{"name": "Push to Github", "assigned_user_id": 1},
{"name": "Update the mailing list", "assigned_user_id": 1}]
}
}
然后我可以像这样解析该 JSON:
NSString *filename = [[NSBundle mainBundle] pathForResource:@"13628140" ofType:@"json"];
NSData *data = [NSData dataWithContentsOfFile:filename];
NSError *error;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data
options:0
error:&error];
NSDictionary *product = dictionary[@"product"];
NSArray *tasks = product[@"tasks"];
NSDictionary *firstTask = tasks[0];
NSString *firstName = firstTask[@"name"];
NSString *firstAssignedUserId = firstTask[@"assigned_user_id"];
或者,如果您想枚举任务:
NSDictionary *product = dictionary[@"product"];
NSArray *tasks = product[@"tasks"];
[tasks enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSDictionary *task = obj;
NSLog(@"Task \"%@\" is assigned to %@", task[@"name"], task[@"assigned_user_id"]);
}];
你只是问如何在 Core Data 中存储 tasks
的 NSArray
?
关于ios - 休息套件 : mapping with nested object with no id (dupplicated),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13628140/