2013-07-19 37 views
0

我想從多個對象中創建一個JSON字符串。基本上我這樣做是爲了將數據庫的一部分發送回服務器,以便它可以更新自上次連接以來完成的操作。我希望能夠將對象字典轉換爲NSData或JSON字符串併發送它,但我試圖調用NSJSONSerialization dataWithJSONObject失敗。任何想法如何最好地解決這個問題?我是否需要分別執行這些對象中的每一個?即使如此,我將如何處理自定義對象的數組。Objective C:試圖用NSArrays,NSDictionaries和自定義對象字典創建JSON字符串

SchedModel *sched = [self retrieveSchedData]; //custom object 
NSArray *event = [self retrieveEvents]; //Array of custom objects 
NSDictionary *info = [self retrieveInfo]; //plain old NSDictionary 

NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; 

// Load all objects into a dictionary 
[dict setObject: sched forKey:@"sched"]; 
[dict setObject: event forKey:@"event"]; 
[dict setObject: info forKey:@"info"]; 

NSError * error = nil; 

//Now create the NSData for this object (THIS FAILS) 
NSData * jsonData = [NSJSONSerialization dataWithJSONObject: dict options:NSJSONReadingMutableContainers error:&error]; 
NSString *JSONString = [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding]; 

回答

0

您不能序列化自定義對象。在序列化之前,您必須將sched轉換爲NSDictionary

+0

是否有一種將sched轉換爲字典的通用方法,或者是否需要在所有自定義對象中創建toDictionary方法? – DaveB

+0

這將是主要的方式,因爲只有你知道應該序列化哪些屬性/ iVars。但是,您可以使用Obj-C運行時檢查所有屬性並對它們進行編碼。 –

+0

你可以看看[Mantle](https://github.com/github/Mantle)那樣做。 –

相關問題