22

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

0

2 Answers 2

31

There is a class specifically made for this, its called 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];
4
  • 3
    Just to add : this API is available in iOS 5 and later
    – Saurabh
    Commented Nov 28, 2012 at 3:31
  • Thanks a lot. I didn't know that existed in Obj-C. That's exactly what I needed. Commented Nov 28, 2012 at 3:32
  • @IIS7Rewrite if this answer is useful for you, please do not forget to mark it as accepted, thanks.
    – Pochi
    Commented Nov 28, 2012 at 3:38
  • @LuisOscar if you thought the question was useful and clear, you should up vote it.
    – Rob
    Commented Nov 28, 2012 at 5:07
6

write:

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

read:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.