Search code examples
c#json.netjson.netjsonconvert

How to Save Large Json Data?


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?


Solution

  • 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 
    });