我在 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/