I am trying to serialize a List to a file in C# with JSON.NET. I want to be able to add values to the list and serialize that change.
I do not want to serialize the list all over again, since it can grow pretty big.
Is something like that possible with JSON.NET?
using (FileStream fs = File.Open(@"c:\list.json", FileMode.CreateNew))
using (StreamWriter sw = new StreamWriter(fs))
using (JsonWriter jw = new JsonTextWriter(sw))
{
jw.Formatting = Formatting.Indented;
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(jw, list);
}
this way it would only be possible to "Reserialize" the whole list, not add changes to the file.
Json.NET has excellent support for serializing and deserializing collections of objects. To serialize a collection - a generic list, array, dictionary, or your own custom collection - simply call the serializer with the object you want to get JSON for.
JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).
Steps to perform serialization in PythonOpen the file in which you want to save the object in binary write mode. Call pickle 's dump() method and pass object as a first argument and the above-created file object as a second argument. Repeat step 3 until all of the objects are saved to a file.
JSON is a format that encodes an object to a string. On the transmission of data or storing is a file, data need to be in byte strings, but as complex objects are in JSON format. Serialization converts these objects into byte strings which is JSON serialization.
In many formats (including json and xml), there is semantic closing of the document at the end; to "append" would require back-tracking through this. In others, there may be length-prefix data much earlier in the file that requires changing. In either event, this will only work reasonably if the list is the last (or only) thing in the file - not a safe assumption in the general case, so serializers don't generally include support for "append at the end" after the fact.
My default answer here, therefore, would be:
either reserialize the entire list, or construct some mechanism of "framing" that allows you to store (and subsequently merge) multiple completely independent fragments (without mutating / extending - just add an extra frame)
Note that some formats do support append; for example, protocol buffers deliberately includes no document closing / length preamble - it is a specific feature of the design that append fragment === merge, which for lists means: add an item. However, this is then not json.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With