在iOS中将Object转换为json

时间:2013-07-16 09:47:55

标签: ios json

我有这个对象:

@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)

如何解决?

1 个答案:

答案 0 :(得分:3)

EmailToSend是您在应用程序中使用的类类型。但是,Cocoa中的内置JSON序列化程序只能使用简单类型,例如NSString NSArray等。如果您希望它工作,则必须使From属性成为字符串

正如Wain在评论中指出的那样,根元素也必须是NSArrayNSDictionary