問題描述
我有一個使用核心數據的應用程序,其中包含 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模板網!