简体   繁体   English

我可以将JSON数据写入iOS / Objective-C中的文件吗?

[英]Can I write JSON data to a file in iOS/Objective-C?

I need to write JSON data to a file using Objective-C. 我需要使用Objective-C将JSON数据写入文件。 My data looks something like this: 我的数据看起来像这样:

data = {
    "NrObjects" : "7",
    "NrScenes" : "5",
    "Scenes" : [
        { "dataType" : "label", "position" : [20, 20, 300, 300], "value" : "Hello" },
        { "dataType" : "label", "position" : [20, 60, 300, 300], "value" : "Hi There" }
    ]
}

It may get more complex than this, but what I need to know is whether I can do this with Obj-C, ie, create an object of this form, write the data to a file, and read it back. 它可能比这更复杂,但我需要知道的是我是否可以使用Obj-C执行此操作,即创建此表单的对象,将数据写入文件,然后将其读回。

There is a class specifically made for this, its called NSJSONSerialization . 有一个专门为此而定的类,它叫做NSJSONSerialization

You read it like this: 你这样读:

NSArray* jsonResponse = [NSJSONSerialization JSONObjectWithData:theResponse
                                                        options:kNilOptions
                                                          error:&error];

and write it like this: 并写这样:

NSData* jsonData = [NSJSONSerialization dataWithJSONObject:userDetails
                                                   options:kNilOptions 
                                                     error:&error];

write: 写:

NSData *data = [NSKeyedArchiver archivedDataWithRootObject:jsonObject];
[data writeToFile:path atomically:YES];

read: 读:

NSData *data = [NSData dataWithContentsOfFile:path];
NSDictionary *jsonObject = [NSKeyedUnarchiver unarchiveObjectWithData:data];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM