使用MagicalRecord导入JSON

时间:2014-02-03 17:16:07

标签: ios iphone json magicalrecord

我有这个JSON文档:

    [
  {
  "category": "Para los invitados",
  "items": [
            {
            "title": "Invitaciones",
            "subtitle": "Sobres, imprenta",
            "items": [
                      "Invitaciones",
                      "Sobres",
                      "Coste envío invitaciones",
                      "Tarjetas de agradecimiento",
                      "Sobres para tarjetas de agradecimiento",
                      "Coste de envío tarjetas de agradecimiento"
                      ]
            },
            <three elements more...>
            ]
  },
<two elements more...>
]

如何使用MagicalRecord导入此文档?任何人都可以粘贴一个例子吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

如果您已完成核心数据模型并包含魔法记录,则可以解析JSON文件:

// Your Json File
NSURL *url = [NSURL URLWithString:@"YOUR_JSON"];
NSData* data = [NSData dataWithContentsOfURL: url];

NSError *error; // For later error handling

NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

// Json values for "items" key
NSDictionary *items = [json valueForKey:@"items"];

// We are going through the items
for(int i = 0; i < [items count]; i++) {

    // We save the title values into our CoreData Model

    NSManagedObjectContext *localContext = [NSManagedObjectContext MR_contextForCurrentThread];

    NSString *title = [[items valueForKey:@"title"] objectAtIndex:i];

    YOUR_MODEL_ENTITY *entity = [YOUR_MODEL_ENTITY MR_createInContext:localContext];

    entity.title = title;

    // We save it
    [localContext MR_saveToPersistentStoreWithCompletion:^(BOOL success, NSError *error) {
                    if (error) {
                        NSLog(@"Couldn't save new title with Magical Record: %@", error);
                    }
                }];
}

我希望它是对的,我写的...... 请查看documentation:)