如何将 JSON 对象保存到 Core Data?

发布于 2025-01-07 15:32:24 字数 549 浏览 7 评论 0原文

我是 Core Data 中的 nwebie,我设计了一个基于导航的应用程序,我使用的一些数据是在运行时创建的(来自通过 JSON 的 URL)。我学习了一些教程并搜索了几乎一天,但仍然没有意识到如何将传入的 JSON 数据保存到我的核心数据模型中的实体(或事件?)。我在 DetailViewController 类中获取数据,并且需要将此数据保存到 Core Data(我已经准备了一个具有 7 个属性的实体)。任何人都可以帮忙吗?(如果您知道一个好的教程或示例代码,我会很高兴)

编辑这可能有点具体,但我确实遇到了麻烦,只需要一点帮助。 我的数据来自一种宁静的服务器(我用 PHP 编写),首先用户输入他/她的登录信息(我之前已将其保存到服务器上的数据库中),当响应数据到来时,我将使用不同的它在不同视图中的元素(例如,user_id 将在一个视图上使用,buttonData 等将在其他视图上使用)。我的问题是,如何将 JSON 数据保存到我的核心数据模型中(目前有树实体)。预先感谢

注意:我四处寻找了很多,但找不到任何关于像我这样的应用程序的答案和教程

I'm a nwebie in Core Data, i have designed a navigation based application and some of the data i use are created on run time(come from a URL via JSON). I took a few tutorials an searched for almost a day but haven't still realized how to save the incoming JSON data to the Entity (or event?) in my Core Data model. I fetch the data in the DetailViewController class and i need to save this data to Core Data(I have prepared an Entity with 7 properties). Can anyone please help?(If you know a good tutorial or sample code i will be pleased)

EDIT This may be a little specific but i really have trouble with and need just a little help.
My data comes to the app from a kind of restful server(i wrote it in PHP), firstly user enters his/her login informations(which i have saved to the database on server before) and when the response data comes i will use different elements of it in differen views(for example the user_id will be used on a view and the buttonData etc on other views). My question is, how will i save JSON data into my core data model(has tree Entities for the moment). Thanks in advance

Note: I lokked arround a lot but couldn't find any answer&tutorial about an app like mine

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

第七度阳光i 2025-01-14 15:32:25

这个库帮助我很多

Features
  • 属性和关系映射到JSON关键路径。

  • 使用命名 NSValueTransformer 对象进行值转换。

  • 对象图保存。

  • 支持实体继承

  • 反之亦然

This lib helps me lot

Features
  • Attribute and relationship mapping to JSON key paths.

  • Value transformation using named NSValueTransformer objects.

  • Object graph preservation.

  • Support for entity inheritance

  • Works vice-versa

心意如水 2025-01-14 15:32:24

最好的方法是创建与 JSON 结构相对应的实体。最简单的情况是每个 JSON 对象成为一个实体,并且数组成为实体数组。但是,要合理,不要对本质上属于其超级对象一部分的 JSON 子对象引入太多的杀伤力。

创建实体后,您可以开始解析和翻译。使用一些 JSON 框架(从 iOS5 开始,Apple 有一个)并将 JSON 字符串解析为对象树,其中根项是 NSArray 或 NSDictionary,子元素将为 NSArray、NSDictionary、NSNumber、NSString 或 NSNull。

在迭代循环中一一检查它们,并根据核心数据实体属性分配值。您可以在此处使用 NSKeyValueCoding 并避免过多手动映射属性名称。如果您的 JSON 属性与实体属性同名,您将能够遍历所有字典元素并将它们解析为同名的属性。

示例

我在类似情况下的解析代码如下:

NSDictionary *parsedFeed = /* your way to get a dictionary */;
for (NSString *key in parsedFeed) {
    id value = [parsedFeed objectForKey:key];
    // Don't assign NSNull, it will break assignments to NSString, etc.
    if (value && [value isKindOfClass:[NSNull class]])
         value = nil;

    @try {
        [yourCreatedEntity setValue:value forKey:property];
    } @catch (NSException *exception) {
        // Exception means such attribute is not defined in the class or some other error.
    }
}

该代码将在简单的情况下工作,但是,根据您的需要,它可能需要扩展:

  • 使用某些类型的自定义映射,以防您希望将 JSON 值放置在不同名称的属性。
  • 如果您的 JSON 具有子对象或子对象数组,您将需要检测这些情况(例如在 setter 中),并启动更深一层的新解析。否则,在我的示例中,您将面临将 NSDictionary 对象分配给 NSManagedObject 的情况。

我认为在这个答案的范围内深入探讨这些更高级的问题是不合理的,因为它会过度扩展它。

The best way to do that would be to create entities corresponding to JSON structure. Easiest was is when each JSON object becomes an entity, and arrays become arrays of entities. Be reasonable, however, and don't introduce too much overkill for JSON subobjects that are essentially part of its superobject.

When you have created entities, you can start off with the parsing and translation. Use some JSON framework (starting from iOS5 there's one from Apple) and parse JSON string into object tree, where root item is either an NSArray or NSDictionary, and subelements will be NSArray, NSDictionary, NSNumber, NSString or NSNull.

Go over them one by one in iterational loops and assign according values to your core data entity attributes. You can make use of NSKeyValueCoding here and avoid too much manual mapping of the attribute names. If your JSON attributes are of the same name as entity attributes, you'll be able to just go over all dictionary elements and parse them into attributes of the same name.

Example

My parsing code in the similar situation was as follows:

NSDictionary *parsedFeed = /* your way to get a dictionary */;
for (NSString *key in parsedFeed) {
    id value = [parsedFeed objectForKey:key];
    // Don't assign NSNull, it will break assignments to NSString, etc.
    if (value && [value isKindOfClass:[NSNull class]])
         value = nil;

    @try {
        [yourCreatedEntity setValue:value forKey:property];
    } @catch (NSException *exception) {
        // Exception means such attribute is not defined in the class or some other error.
    }
}

This code will work in trivial situation, however, it may need to be expanded, depending on your needs:

  • With some kinds of custom mappings in case you want your JSON value be placed in differently named attribute.
  • If your JSON has sub-objects or arrays of sub-objects, you will need to detect those cases, for example in setters, and initiate new parsing one level deeper. Otherwise with my example you will face the situation that assigns NSDictionary object to an NSManagedObject.

I don't think it is reasonable to dive into these, more advanced matters in scope of this answer, as it will expand it too much.

献世佛 2025-01-14 15:32:24

我建议您使用这个库: https://github.com/TouchCode/TouchJSON
然后,如果您想创建一个工厂来解析 json 并提供代码数据,则可以使用选择器调用方法来填充所有属性。

I suggest you to use this library : https://github.com/TouchCode/TouchJSON
And then if you want to make a factory to parse json and feed your code data, you can use selectors to call methods to fill all your attributes.

晨曦÷微暖 2025-01-14 15:32:24

您的 JSON 数据很可能会转换为 NSDictionary 或 NSArray(或两者的某种组合)。只需从 JSON 结构中提取键/值并将它们添加到实体类中即可。

Chances are your JSON data gets converted to an NSDictionary or NSArray (or some combination of the two). Simply extract the key/values from the JSON structure and add them to your entity class.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文