【问题标题】:Import JSON using MagicalRecord [duplicate]使用 MagicalRecord 导入 JSON [重复]
【发布时间】:2014-02-03 17:16:06
【问题描述】:

我有这个 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 导入此文档?谁能贴个例子?

谢谢!

【问题讨论】:

  • 是的,但我需要一些帮助来创建关系(CoreData 模型中的 userInfo 属性?)。你能帮我吗?

标签: ios iphone json magicalrecord


【解决方案1】:

如果你已经完成了一个核心数据模型并包含了 Magical Record,你可以解析 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 :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-23
    • 2013-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-13
    相关资源
    最近更新 更多