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

时间:2023-05-03
本文介绍了NSJSONSerialization 出错 - JSON 写入中的类型无效(菜单)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

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

I have an App using core data with 3 entities with very similar attributes. The relationship is such as:

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

Branch ->> Menu ->> Category ->> FoodItem

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

Each entity has an associated class: example

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

But instead of JSON, i get a SIGABRT error.

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

任何想法如何修复它或如何使实体类(分支、菜单等)JSON 序列化兼容?

Any ideas how to fix it or how to make the entity classes (Branch, Menu etc) JSON serialization compatible?

推荐答案

那是因为你的菜单"类在 JSON 中是不可序列化的.基本上,该语言不知道您的对象应该如何在 JSON 中表示(要包含哪些字段,如何表示对其他对象的引用......)

That's because your "Menu" class is not serializable in JSON. Bascially the language doesn't know how your object should be represented in JSON (which fields to include, how to represent references to other objects...)

来自 NSJSONSerialization 类参考

可以转换为 JSON 的对象必须具有以下内容属性:

An object that may be converted to JSON must have the following properties:

  • 顶级对象是 NSArray 或 NSDictionary.
  • 所有对象都是 NSString、NSNumber、NSArray、NSDictionary 或 NSNull 的实例.
  • 所有字典键都是 NSString 的实例.
  • 数字不是 NaN 或无穷大.

这意味着该语言知道如何序列化字典.因此,从菜单中获取 JSON 表示的一种简单方法是提供 Menu 实例的 Dictionary 表示,然后将其序列化为 JSON:

This means that the language knows how to serialize dictionaries. So a simple way to get a JSON representation from your menu is to provide a Dictionary representation of your Menu instances, which you will then serialize into 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]);

这篇关于NSJSONSerialization 出错 - JSON 写入中的类型无效(菜单)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:iOS 获取已安装的配置文件 下一篇:iOS 5:数据加密 AES-256 EncryptWithKey:未找到

相关文章

最新文章