2013-07-16 118 views
1

我有這樣的對象:
轉換對象到JSON在iOS的

@interface EmailToSend : NSObject 

@property (copy, nonatomic) NSString *Subject; 
@property (copy, nonatomic) NSString *Body; 
@property (strong, nonatomic) NSArray *Cc; 
@property (strong, nonatomic) NSArray *Bcc; 
@property (strong, nonatomic) NSArray *To; 
@property (strong, nonatomic) EmailAddress *From; 
@property (copy, nonatomic) NSString *Username; 
@property (copy, nonatomic) NSString *Password; 

@end 

Bcc, To, From as Array EmailAdress 

@interface EmailAddress : NSObject 

@property (nonatomic, assign) int Id; 
@property (copy, nonatomic) NSString *address; 
@property (copy, nonatomic) NSString *displayName; 

@end 

我使用iOS中的JSON框架解析對象EmailToSend

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

當我運行該項目,會出現一個錯誤:

Terminating app due to uncaught exception 
'NSInvalidArgumentException', reason: 'Invalid type in JSON write 
(EmailToSend) 

如何解決?

+0

它在錯誤消息中說明了這一切:'JSON寫入(EmailToSend)'中的無效類型'。這可能是你自己的課程之一。 – dandan78

+0

@NhuHowHow你已經解決了這個問題,我面臨着同樣的問題。 –

回答

3

EmailToSend是您在應用程序中使用的類類型。但是,Cocoa中的內置JSON序列化程序只能使用簡單的類型,例如NSStringNSArray等。如果您希望它可以工作,則必須使From屬性成爲一個字符串。

正如Wain在他的評論中指出的,根元素還需要是NSArrayNSDictionary

+0

根元素應該是一個字典或一個數組。 – Wain

+0

感謝您的額外信息。 – dandan78