我一直在尝试创建一个类,以允许我将核心数据输出到JSON。
我设法使它工作到一定程度,但是我似乎在输出关系上遇到了麻烦
NSMutableArray * objectsArray = [[NSMutableArray alloc] init];
for (NSManagedObject * object in array) {
if([NSJSONSerialization isValidJSONObject:object]) {
[objectsArray addObject:object];
} else {
NSMutableDictionary *fields = [NSMutableDictionary dictionary];
for (NSAttributeDescription *attribute in [[object entity] properties]) {
NSString *attributeName = attribute.name;
id attributeValue = [object valueForKey:attributeName];
if([results length] > 0)
{
NSArray *chunks2 = [results componentsSeparatedByString: @","];
for (NSString * string in chunks2) {
if([string.lowercaseString isEqualToString:attributeName.lowercaseString])
{
[fields setObject:[NSString stringWithFormat:@"%@",attributeValue] forKey:attributeName];
break;
}
}
}
else
{
if (attributeValue) {
[fields setObject:[NSString stringWithFormat:@"%@",attributeValue] forKey:attributeName];
}
}
}
[objectsArray addObject:fields];
}
}
NSError *error;
NSData * JSONData = [NSJSONSerialization dataWithJSONObject:objectsArray options:kNilOptions error:&error];
只要我没有任何关系,例如一个->很多或很多->一个,这就可以很好地输出数据
它输出以下内容
{
"mySegmentation": "(null)",
"number": "9452062"
},
{
"mySegmentation": "<NSManagedObject: 0x212050b0> (entity: SegmentationCodes; id: 0x212090b0 <x-coredata://BEC52F5F-EA26-4CFF-BCCB-09DA163F465D/SegmentationCodes/p13> ; data: <fault>)",
"number": "9448502"
},
如何获得缩进关系中的信息并从中输出信息?
我已经为此花了一段时间的头,感谢您的帮助
谢谢马特
从文档中:
可能转换为JSON的对象必须具有以下属性:
因此,您要做的是用字典,数组,字符串,数字,空值组成字典或数组。
通常,CoreData中的关系不会排序,因此NSSet必须从该集合生成一个NSArray(因此存在Apple提供的一种不错的方法),并将其作为值存储在特定键的字典中。
然后运行- dataWithJSONObject:options:error:
示例(如您之前所做的那样)并检索正确的JSON。
不确定缩进是否正确。您必须检查一下。
就是这样,希望
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句