このタスク オブジェクトをどのようにマッピングするかはよくわかりませんが、次の方法NSData
で JSON 文字列を解析します。
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data
options:0
error:&error];
その場合、NSDictionary
「product」という 1 つのキーで を取得し、そのキーのオブジェクトは別の辞書です。NSDictionary
「タスク」をキーに持つオブジェクトはNSArray
、4 つのNSDictionary
オブジェクトのうちの 1 つです。
さて、その 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"]);
}];
NSArray
それをtasks
コアデータに保存する方法を尋ねているだけですか?