ios - 将数组从 Core Data 转换为 JSON 字符串的最佳方法?

标签 ios objective-c json

我在 Core Data 中有一些数据,我想将其转换为字符串,以便将其发送回我的 Web 服务器。这是我到目前为止的代码:

NSError *error = nil;
NSFetchRequest *unfinishedTime = [[NSFetchRequest alloc] init];

NSEntityDescription *timeEntity = [NSEntityDescription entityForName:@"TimeEntries" inManagedObjectContext:context];
[unfinishedTime setEntity:timeEntity];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"timeStart != nil AND timeEnd != nil"];
[unfinishedTime setPredicate:predicate];

NSArray *timeArray = [context executeFetchRequest:unfinishedTime error:&error];

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:timeArray options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

它在 NSData 行上给我一个错误。据我所知,timeArray 中有 5 个对象。我确信这是一个非常简单的错误,我可能会以完全错误的方式解决这个问题。

最佳答案

根据 NSJSONSerialization's documentation ...

An object that may be converted to JSON must have the following properties:

The top level object is an NSArray or NSDictionary. All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull. All dictionary keys are instances of NSString. Numbers are not NaN or infinity.

在你的例子中,顶级对象是一个 NSArray 但所有对象都是 NSManagedObject 的实例(或者它的自定义子类,如果你是这样设置的)你的项目)。

可能最简单的解决方法是:

unfinishedTime.resultType = NSDictionaryResultType;

这样 Core Data 将返回一个字典数组而不是一个托管对象数组,这些对象是 JSON 序列化程序知道如何序列化的对象。

关于ios - 将数组从 Core Data 转换为 JSON 字符串的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17843656/

相关文章:

php - 我无法使用 sql 查询数据填充数组以将其导出为 php 中的 json 对象

ios - iPad 缺少 OpenGL 扩展字符串 GL_APPLE_texture_2D_limited_npot

ios - 动态 UIPickerView 菜单

objective-c - Objective C 库和搜索路径

json - 如何通过 ARM 模板在应用程序网关中创建 backendAddressPools、frontendports 的多个实例

python - 使用 Graph API 在 Facebook 中定位帖子的地理定位

jquery - 使用 jquery mobile 和 html5 的标签栏 iOS 应用程序

ios - 避免用户注册系统,但需要应用内购买和数据同步

ios - 如何在 iOS 中创建 AppDelegate 共享实例?

objective-c - 如何在 objective-c 中创建 BOOL 实例变量?