OGeek|极客世界-中国程序员成长平台

标题: ios - NSJSONSerialization - 核心数据与 JSON 的关系 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 12:11
标题: ios - NSJSONSerialization - 核心数据与 JSON 的关系

我一直在尝试创建一个类以允许我将核心数据输出到 JSON。

我已经设法让它工作到一定程度,但是我似乎在输出关系上遇到了障碍

NSMutableArray * objectsArray = [[NSMutableArray alloc] init];

for (NSManagedObject * object in array) {
    if([NSJSONSerialization isValidJSONObjectbject]) {
        [objectsArray addObjectbject];
    } 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 dataWithJSONObjectbjectsArray 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"
},

我怎样才能让它也缩进并输出关系中的信息?

我一直在为此摸不着头脑,希望能得到帮助

谢谢马特



Best Answer-推荐答案


来自文档:

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

所以,你要做的就是用字典、数组、字符串、数字、空值组成一个字典或数组。

CoreData 中的关系通常是不排序的,所以 NSSets,你必须从集合中生成一个 NSArray(因此存在 Apple 的一个很好的方法)并将其作为特定键的值放入字典中。

然后运行 ​​- dataWithJSONObjectptions:error: 例如(如您之前所做的)并检索正确的 JSON。

不确定缩进是否正确。你必须检查一下。

希望如此

关于ios - NSJSONSerialization - 核心数据与 JSON 的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17492514/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4