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

Vai*_*arg 51 iphone serialization json objective-c ios5

我有一个应用程序使用核心数据与3个具有非常相似属性的实体.这种关系如下:

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

每个实体都有一个关联的类: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]);
Run Code Online (Sandbox Code Playgroud)

但是我没有使用JSON,而是出现了SIGABRT错误.

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

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

Jul*_*ien 82

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

来自NSJSONSerialization类参考

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

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

这意味着该语言知道如何序列化字典.因此,从菜单中获取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];
}
Run Code Online (Sandbox Code Playgroud)

你可以像这样使用它:

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]);
Run Code Online (Sandbox Code Playgroud)


Edw*_*ynh 24

有一类方法isValidJSONObjectNSJSONSerialization,告诉你,如果一个对象可以序列化.正如朱利安指出你可能需要将你的对象转换为NSDictionary.NSManagedModel提供了一些方便的方法来获取实体的所有属性.所以你可以创建一个类别NSManagedObject,有一个方法将其转换为NSDictionary.这样,您就不必toDictionary为要转换为字典的每个实体编写方法.

@implementation NSManagedObject (JSON)

- (NSDictionary *)toDictionary
{
    NSArray *attributes = [[self.entity attributesByName] allKeys];
    NSDictionary *dict = [self dictionaryWithValuesForKeys:attributes];
    return dict;
}
Run Code Online (Sandbox Code Playgroud)