使用Json.Net序列化对象会导致Out of Memory异常

时间:2014-09-30 19:15:36

标签: c# serialization windows-store-apps json.net out-of-memory

免责声明:我确实完成了这里提供的大部分解决方案,但大部分都是在反序列化时讨论OOM异常。

我正在尝试使用Json.Net将对象(它的树)序列化为Json。一切都适用于小对象,但当我尝试大对象时,我得到OOM异常。因为它适用于相同数据类型的较小对象,我假设没有循环引用(我确实检查了我的数据结构)。 有没有办法可以将我的对象转换为流(这是一个Windows应用商店应用)并使用该流生成Json?

 public static async Task<bool> SerializeIntoJson<T>(string fileName, StorageFolder destinationFolder, Content content)
    {
        ITraceWriter traceWriter = new MemoryTraceWriter();
        try
        {

            string jsonString = JsonConvert.SerializeObject(content, Formatting.Indented, new JsonSerializerSettings
            {
                PreserveReferencesHandling = PreserveReferencesHandling.Objects,
                TypeNameHandling = TypeNameHandling.All,
                Error = ReportJsonErrors,
                TraceWriter = traceWriter,
                StringEscapeHandling = StringEscapeHandling.EscapeNonAscii
            });
            System.Diagnostics.Debug.WriteLine(traceWriter);

            StorageFile file = await destinationFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
            await Windows.Storage.FileIO.WriteTextAsync(file, jsonString);
            return true;
        }
        catch (NullReferenceException nullException)
        {
            System.Diagnostics.Debug.WriteLine(traceWriter);
            logger.LogError("Exception happened while serializing input object, Error: " + nullException.Message);
            return false;
        }
        catch (Exception e)
        {
            System.Diagnostics.Debug.WriteLine(traceWriter);
            logger.LogError("Exception happened while serializing input object, Error: " + e.Message, e.ToString());
            return false;
        }
    }

为了将我的对象转换为流,我发现的代码使用的是BinaryFormatter,这在Windows商店应用程序dll中是不可用的。

2 个答案:

答案 0 :(得分:8)

It is due to very large number of records you are trying to serialize, which occupies large memory. Solutions which I have found for this error as directly writing to the documents using StreamWriter(JsonWriter or TextWriter).

If you have Object use TextWrite

using (TextWriter textWriter = File.CreateText("LocalJsonFile.json"))
{
    var serializer = new JsonSerializer();
    serializer.Serialize(textWriter , yourObject);
}

If you have string use StringWriter

  StringBuilder sb = new StringBuilder();
  StringWriter sw = new StringWriter(sb);

  using(JsonWriter textWriter = new JsonTextWriter(sw))
  {
     var serializer = new JsonSerializer();
     serializer.Serialize(textWriter, yourObject);
  }

答案 1 :(得分:4)

根据对问题的评论中的建议更新了代码,这有效!

public static async Task<bool> SerializeIntoJson<T>(string fileName, StorageFolder destinationFolder, Content content)
    {
        try
        {
            StorageFile file = await destinationFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
            using (var stream = await file.OpenStreamForWriteAsync())
            {

                StreamWriter writer = new StreamWriter(stream);
                JsonTextWriter jsonWriter = new JsonTextWriter(writer);
                JsonSerializer ser = new JsonSerializer();

                ser.Formatting = Newtonsoft.Json.Formatting.Indented;
                ser.PreserveReferencesHandling = PreserveReferencesHandling.Objects;
                ser.TypeNameHandling = TypeNameHandling.All;
                ser.Error += ReportJsonErrors;

                ser.Serialize(jsonWriter, content);

                jsonWriter.Flush();

            }
            return true;
        }
        catch (NullReferenceException nullException)
        {

            logger.LogError("Exception happened while serializing input object, Error: " + nullException.Message);
            return false;
        }
        catch (Exception e)
        {

            logger.LogError("Exception happened while serializing input object, Error: " + e.Message, e.ToString());
            return false;
        }
    }
相关问题