iphone - 将JSON写入文件。但是你怎么读回来呢?

标签 iphone objective-c ios xcode

我将JSON写入文件:

NSData *jsonData = [[CJSONSerializer serializer] serializeObject:dictionary error:&error];
[jsonData writeToURL:[NSURL fileURLWithPath:[NSString stringWithFormat:@"%@%@",
NSTemporaryDirectory(), @"file.json"]] atomically:YES];

但是我怎么读回来呢?

我尝试将文件加载到NSData中,然后像这样转换为NSDictionary
    // uses toll-free bridging for data into CFDataRef and CFPropertyList into NSDictionary
CFPropertyListRef plist =  CFPropertyListCreateFromXMLData(kCFAllocatorDefault, (CFDataRef)data,
                                                           kCFPropertyListImmutable,
                                                           NULL);
// we check if it is the correct type and only return it if it is
if ([(id)plist isKindOfClass:[NSDictionary class]])
{
    return [(NSDictionary *)plist autorelease];
}
else
{
    // clean up ref
    CFRelease(plist);
    return nil;
}

但是它崩溃了,因为我认为NSData不是plist。

CJSONSerializer有没有一种方法可以从文件中提取数据并将其转换为字典?

谢谢,
-码

最佳答案

您可以使用序列化器将对象转换为JSON,并使用反序列化器将其转换为相反的方向。实际上,TouchJSON具有CJSONDeserializer类:

[[CJSONDeserializer deserializer] deserialize:data error:NULL];

关于iphone - 将JSON写入文件。但是你怎么读回来呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8473495/

相关文章:

iphone - UIButton 禁用和启用背景图像

ios - 在 FSCalendar 中添加自定义假期

ios - NSCoding:自定义类未归档,但类成员为空/无

ios - 链接点击监听器上的 WKWebView?

iphone - 捕获来自 Singleton 的更改

iphone - UITableView rowHeight 空中变化

ios - ASIHTTPRequest 下载 : Should I request a large file or many small size files?

ios - Xcode 项目变坏了 - 忘记设备并任意取消构建

ios - 段错误 11 仅适用于 xcode 10 swift 3

iphone - 调用 popToRootViewControllerAnimated :NO, 将 animate 设置为 YES 时崩溃,工作没有崩溃,奇怪。