0

i have a large ObservableCollection that I want to get out as Json file. I used the following code, But I get an error out of memory

string json = JsonConvert.SerializeObject(content, Formatting.Indented);
await File.WriteAllTextAsync("file.json");

How can I save this huge ObservableCollection in a json file?

dbc
  • 104,963
  • 20
  • 228
  • 340
Atena
  • 109
  • 2
  • 9
  • Something to think about: Is the consumer of this file also also going to have problems when it tries to load it? – Wyck Jan 03 '22 at 20:27
  • @Wyck no i dont need to load it, i only want to save it. – Atena Jan 03 '22 at 20:29
  • `WriteAllTextAsync` takes (at least) two arguments. Your example is missing the text to be written. You probably meant `WriteAllTextAsync("file.json", json)` – Wyck Jan 03 '22 at 20:31
  • If you don't need to load it, ever, just do `File.WriteAllBytes("file.json", new byte[0]);`. It'll be empty, but since you don't need to load it, the contents shouldn't matter, so you can save some disk space in the process. – Lasse V. Karlsen Jan 03 '22 at 21:31

2 Answers2

4

Instead of serializing to a string, and then writing the string to a stream, stream it directly:

using var stream = File.Create("file.json");
JsonSerializer.Serialize(stream, content, new JsonSerializerOptions
{
    WriteIdented = true 
});
Blindy
  • 65,249
  • 10
  • 91
  • 131
1

try to serialize directly to the file.This way Newtosoft https://www.newtonsoft.com/json/help/html/serializewithjsonserializertofile.htm recomends to do it

using (StreamWriter file = File.CreateText(@"c:\file.json"))
    {
        JsonSerializer serializer = new JsonSerializer();
        serializer.Serialize(file, content);
    }
Serge
  • 40,935
  • 4
  • 18
  • 45