AlgoCoder
AlgoCoder

Reputation: 1696

Add/Edit JSON data iOS?

I am using the below code to fetch JSON data from my local drive. It works quite well

Now I want to add my JSON data to the Same URL

I don't want create and replace the previous json file

Is it possible??

Is there any easy way to do it??

NSURL *fileUrl=[NSURL URLWithString:@"localDriveURL"];
//NSData *data = [NSData dataWithContentsOfFile:filePath];
NSData *data=[NSData dataWithContentsOfURL:fileUrl];
NSError* error;

NSArray* json = [NSJSONSerialization JSONObjectWithData:data //1
                                                     options:NSJSONReadingMutableContainers
                                                       error:&error];

NSArray *json2=[json valueForKey:@"locations"];

for (int i=0; i<json2.count; i++) {

}

Upvotes: 1

Views: 3941

Answers (2)

Wain
Wain

Reputation: 119031

If the file is part of the app bundle, you can't change anything about it.

Generally speaking you do want to replace the existing file.

While you could use NSFileHandle to write additional data into the file it is relatively complex and relatively likely to corrupt the JSON (when you make an indexing mistake or something like that).

Your best option is to read the data in mutable (as you are), then modify and use NSJSONSerialization to convert back to data again, then save that data to disk (replacing the original).

Your current code should really be:

NSMutableArray* json = [...

because of the mutable container option you're using.

You can then add some new items to the array:

[json addObject:@"Stuff"];
[json insertObject:@"Other Stuff" atIndex:0];

Then re-save:

data = [NSJSONSerialization dataWithJSONObject:json options:nil error:&error];
[data writeToURL:fileUrl atomically:YES];

Upvotes: 4

Jeef
Jeef

Reputation: 27285

In my code I append JSON to an open file with the following (well I actually made a macro)

I do it both with the serialization and just normal text I type to format it a little better:

For normal text I made a macro to append:

#define jsonAppend(X) [outStream write:[[@X dataUsingEncoding:NSUTF8StringEncoding] bytes] maxLength:[@X lengthOfBytesUsingEncoding:NSUTF8StringEncoding]]

-> you would have to open an output stream to your file and queue it up to the end I would suppose but in my code I just call

jsonAppend("WhatEverIwAntToAppend");

And as far as appending to an existing JSON structure:

[NSJsonSerialization writeJSONObject:My-Dictionary-Object toStream:outStream options:1 error:&error]

Again as long as you have a file handle it should be easy.

With regards to how to open a stream in append mode check: https://developer.apple.com/library/mac/documentation/cocoa/reference/foundation/classes/nsoutputstream_class/reference/reference.html

Upvotes: 0

Related Questions