【问题标题】:Convert NSmangedObject to JsonModel将 NSmangedObject 转换为 JsonModel
【发布时间】:2016-02-08 04:39:57
【问题描述】:
在我的应用程序中,我使用 JsonModel 来解析来自服务器的 JSON 响应,并将其存储在 Core Data 中时,我使用的是 Apple 自己提供的 NSManagedObject 和 NSManagedContext。现在,每当我获取时,我都想将NSManagedObject 转换为 JsonModel。现在的问题是我必须使用两个单独的类来管理 jsonModel 和 NSManagedObject。
【问题讨论】:
标签:
ios
objective-c
core-data
jsonmodel
【解决方案1】:
您可以从此链接获得帮助。
Get Core Data objects to JSON
或者从andrew-madsen的回答中轻松获得
NSManagedObject *managedObject = ...;
NSArray *keys = [NSArray arrayWithObjects:@"key1", @"key2", ..., nil]; // These are the keys for the properties of your managed object that you want in the JSON
NSString *json = [[managedObject dictionaryWithValuesForKeys:keys] JSONRepresentation];
更多详情请点击此链接
nsmanagedobject-to-json
【解决方案2】:
希望对您有所帮助。首先尝试将您的NSMangedObject 转换为NSDictionary。
NSArray *keys = [[[yourObject entity] attributesByName] allKeys];
NSDictionary *dict = [myObject dictionaryWithValuesForKeys:keys];
如果需要,您必须将 dict 用作 JSON 或将它们转换为 JSON 字符串。