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

时间:2021-07-31 22:25:46

I need to write JSON data to a file using Objective-C. My data looks something like this:

我需要使用Objective-C将JSON数据写入文件。我的数据看起来像这样:

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, i.e., create an object of this form, write the data to a file, and read it back.

它可能比这更复杂,但我需要知道的是我是否可以使用Obj-C执行此操作,即创建此表单的对象,将数据写入文件并将其读回。

2 个解决方案

#1


27  

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];

#2


4  

write:

写:

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

read:

读:

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

#1


27  

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];

#2


4  

write:

写:

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

read:

读:

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