gvivetapl
gvivetapl

Reputation: 465

SerializeObject throws System.OutOfMemoryException

I have a serious problem with "JsonConvert.SerializeObject" I need to serialize more than 500,000 dictionary records to make serialize throws the following error; System.OutOfMemoryException. I tried to serialize each key, value pair individually in a foreach but it's locked. Apparently it is an optimization problem, but I do not know where to start, threads to serialize in parts? These functions works fine with few values. My code:

string json = JsonConvert.SerializeObject(DatatableToDictionary(dt), Newtonsoft.Json.Formatting.Indented);

public List<Dictionary<string, object>> DatatableToDictionary(DataTable dt, List<DataColumn> columns)
{
    return dt.Rows.Cast<DataRow>().Select(
         r => columns.ToDictionary(c => c.ColumnName, c => r[c.ColumnName])).ToList();
}

Upvotes: 5

Views: 6438

Answers (1)

mason
mason

Reputation: 32694

When you're dealing with a large amount of data, you can stream it to a file to avoid having it all in memory at once.

var filePath = @"C:\somewhere.json";

using (var fs = File.Open(filePath, FileMode.CreateNew))
using (var sw = new StreamWriter(fs))
using (var jw = new JsonTextWriter(sw))
{
    var serializer = new JsonSerializer();
    serializer.Serialize(jw, dictionary);
}

This will serialize a bit at a time and avoid having a giant string in memory.

Upvotes: 5

Related Questions