Add/Edit JSON data iOS?

后端 未结 2 1842
你的背包
你的背包 2021-02-11 10:39

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 w

相关标签:
2条回答
  • 2021-02-11 11:03

    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

    0 讨论(0)
  • 2021-02-11 11:13

    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];
    
    0 讨论(0)
提交回复
热议问题