2013-07-24 106 views
0

我在核心数据中有一些数据,我想将其转换为字符串,以便我可以将其发送回我的Web服务器。这是我到目前为止的代码:将数组从核心数据转换为JSON字符串的最佳方法?

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个对象。我敢肯定,这是一个非常简单的错误,我可能会以这种错误的方式来解决这个问题。

+0

我为所有核心数据模型写了toDictionary方法。当我需要将它们转换为JSON或记录它时,它变得很容易。 – JeffRegan

回答

3

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; 

这样的核心数据将返回字典的数组,而不是管理对象,这是对象JSON串行器知道如何连载的数组。

+0

有趣的是,我试图将数组变成字典,但我不知道如何。我明天会试试这个。 – Keith

+1

这样做似乎工作,但我有另一个错误:'在JSON写入(__NSDate)'无效类型'。我的核心数据有几个日期字段,JSON无法处理它们。有没有简单的方法来转换它们,或者我必须循环访问数组并手动执行它? – Keith

0

尝试把“kNilOptions”选项,而不是“NSJSONWritingPrettyPrinted”

相关问题