iphone - NSJSONSerialization 出错 - JSON 写入中的类型无效(菜单)

标签 iphone objective-c json serialization ios5

我有一个使用核心数据的应用程序,其中包含 3 个具有非常相似属性的实体。关系是这样的:

分店 ->> 菜单 ->> 分类 ->> FoodItem

每个实体都有一个关联的类:示例

enter image description here

我正在尝试在 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/

相关文章:

使用表单例份验证在 ASP.NET MVC 3 中对 JSON 的 Javascript 请求结果

javascript - 在控制台中显示 JSON 键

iphone - 应用图标(57 * 57)和大图标(512 * 512)应该是同一张图片吗?

ios - 如何在 iOS 数字键盘上显示 "Done"按钮?

iphone - 如何让我的 iPhone 应用程序在 iPhone 的 native 照片应用程序共享菜单中列出?

objective-c - 如何通过 NSJSONSerialization 在 JSON 中包含空值?

iphone - 如何从 iPhone 获取生日联系人列表

ios - 通过 segue 传回 NSNumber

iphone - 从核心数据 iphone 中的数据生成 XML

javascript 窗口 ['func' ] 参数返回未定义而不是函数