2015-02-07 86 views
-2

我在编写自定义对象(房间)的NSMutableArray 数组时遇到问题。 我的自定义对象是:-nameRoom(NSString)-numberRoom(NSInteger)。JSON编码错误

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

这是错误: 终止应用程序由于未捕获的异常 'NSInvalidArgumentException',原因:“无效的类型JSON写(室)

感谢。

回答

1

JSON不支持自定义对象。

参见:Introducing JSON

为了支持自定义对象,您必须将其分解为标准JSON对象的图形。在OP的情况下,它只是一个包含nameRoomnumberRoom的字典。

3

From the docs(是的,有时阅读文档是有帮助的)

You use the NSJSONSerialization class to convert JSON to Foundation objects and convert Foundation objects to JSON.

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.

Other rules may apply. Calling isValidJSONObject: or attempting a conversion are the definitive ways to tell if a given object can be converted to JSON data.

+1

阅读该文档:TL; d;这是互联网教程,Git&SO世代。 – zaph 2015-02-07 14:40:45

+0

几年来,我认为'tl; dr'是畸形的html实体,并且想知道为什么它们到处都出现,直到一位年轻的同事告诉我,这意味着什么。我拥有的第一个“现在我很老”的时刻之一。 – vikingosegundo 2015-02-07 17:11:23

+0

同样在这里,我还是落后了。但是,我敢打赌,你比我年轻。 ;-) – zaph 2015-02-07 20:01:35