我有一个使用核心数据的应用程序,其中包含 3 个具有非常相似属性的实体。关系是这样的:
分店 ->> 菜单 ->> 分类 ->> FoodItem
每个实体都有一个关联的类:示例
我正在尝试在 sqlite 数据库中生成数据的 JSON 表示。
//gets a single menu record which has some categories and each of these have some food items
id obj = [NSArray arrayWithObject:[[DataStore singleton] getHomeMenu]];
NSError *err;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:obj options:NSJSONWritingPrettyPrinted error:&err];
NSLog(@"JSON = %@", [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
但是我得到一个 SIGABRT 错误,而不是 JSON。
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (Menu)'
任何想法如何修复它或如何使实体类(分支、菜单等)JSON 序列化兼容?
最佳答案
那是因为您的“菜单”类在 JSON 中是不可序列化的。基本上,该语言不知道您的对象应该如何在 JSON 中表示(要包含哪些字段,如何表示对其他对象的引用......)
来自 NSJSONSerialization Class Reference
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.
这意味着该语言知道如何序列化字典。因此,从菜单中获取 JSON 表示的一种简单方法是提供 Menu 实例的 Dictionary 表示,然后将其序列化为 JSON:
- (NSDictionary *)dictionaryFromMenu:(Menu)menu {
[NSDictionary dictionaryWithObjectsAndKeys:[menu.dateUpdated description],@"dateUpdated",
menu.categoryId, @"categoryId",
//... add all the Menu properties you want to include here
nil];
}
你可以这样使用它:
NSDictionary *menuDictionary = [self dictionaryFromMenu:[[DataStore singleton] getHomeMenu]];
NSError *err;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:menuDictionary options:NSJSONWritingPrettyPrinted error:&err];
NSLog(@"JSON = %@", [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
关于iphone - NSJSONSerialization 出错 - JSON 写入中的类型无效(菜单),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9893217/