NSJSONSerialization 错误 - JSON 写入中的无效类型(菜单)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9893217/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error with NSJSONSerialization - Invalid type in JSON write (Menu)
提问by Vaibhav Garg
I have an App using core data with 3 entities with very similar attributes. The relationship is such as:
我有一个使用核心数据的应用程序,其中包含 3 个具有非常相似属性的实体。关系是这样的:
Branch ->> Menu ->> Category ->> FoodItem
分店 ->> 菜单 ->> 类别 ->> 食品
Each entity has an associated class: example
每个实体都有一个关联的类:example


I am trying to generate JSON representation of the data in sqlite database.
我正在尝试在 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]);
But instead of JSON, i get a SIGABRT error.
但不是 JSON,而是 SIGABRT 错误。
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (Menu)'
Any ideas how to fix it or how to make the entity classes (Branch, Menu etc) JSON serialization compatible?
任何想法如何修复它或如何使实体类(分支、菜单等)JSON 序列化兼容?
回答by Julien
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...)
那是因为您的“菜单”类在 JSON 中不可序列化。基本上,该语言不知道您的对象应该如何在 JSON 中表示(要包含哪些字段,如何表示对其他对象的引用......)
From the 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 的对象必须具有以下属性:
- 顶级对象是 NSArray 或 NSDictionary。
- 所有对象都是 NSString、NSNumber、NSArray、NSDictionary 或 NSNull 的实例。
- 所有字典键都是 NSString 的实例。
- 数字不是 NaN 或无穷大。
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:
这意味着该语言知道如何序列化字典。因此,从菜单中获取 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];
}
And you could will use it like this :
你可以像这样使用它:
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]);
回答by Edward Huynh
There is a class method isValidJSONObjecton NSJSONSerializationthat tells you if a object can be serialised. As Julien pointed out you probably have to convert your object to a NSDictionary. NSManagedModelprovides some handy methods to get all your attributes for your entity. So you could create a category for NSManagedObjectthat has a method to convert it over to a NSDictionary. This way you don't have to write a toDictionarymethod for each entity you want to convert to a dictionary.
有一类方法isValidJSONObject上NSJSONSerialization,告诉你,如果一个对象可以序列化。正如朱利安指出的那样,您可能必须将对象转换为NSDictionary. NSManagedModel提供了一些方便的方法来获取实体的所有属性。因此,您可以为其创建一个类别,NSManagedObject该类别具有将其转换为NSDictionary. 这样您就不必toDictionary为要转换为字典的每个实体编写方法。
@implementation NSManagedObject (JSON)
- (NSDictionary *)toDictionary
{
NSArray *attributes = [[self.entity attributesByName] allKeys];
NSDictionary *dict = [self dictionaryWithValuesForKeys:attributes];
return dict;
}
回答by Fatih Aksu
You can use + isValidJSONObject: method of NSJSONSerialization class. If it is not valid, you can use - initWithData:encoding: method of NSString.
您可以使用 + isValidJSONObject: NSJSONSerialization 类的方法。如果无效,可以使用 - initWithData:encoding: NSString 的方法。
- (NSString *)prettyPrintedJson:(id)jsonObject
{
NSData *jsonData;
if ([NSJSONSerialization isValidJSONObject:jsonObject]) {
NSError *error;
jsonData = [NSJSONSerialization dataWithJSONObject:jsonObject
options:NSJSONWritingPrettyPrinted
error:&error];
if (error) {
return nil;
}
} else {
jsonData = jsonObject;
}
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
回答by jonypz
I had the key switched with the value : @{value :@"key"} It should be @{@"key":value}
我用值切换了键:@{value :@"key"} 它应该是@{@"key":value}

