Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SerializeObject throws System.OutOfMemoryException

Tags:

c#

json.net

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();
}
like image 432
gvivetapl Avatar asked Sep 20 '16 15:09

gvivetapl


1 Answers

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.

like image 53
mason Avatar answered Oct 11 '22 06:10

mason