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

Jac*_*060 7 c# serialization out-of-memory json.net windows-store-apps

免责声明:我确实完成了这里提供的大部分解决方案,但大部分都是在反序列化时讨论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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

Dil*_*165 8

这是由于您尝试序列化的记录数量非常大,占用大量内存.我发现此错误的解决方案是使用StreamWriter(JsonWriter或TextWriter)直接写入文档.

如果你有Object使用TextWrite

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

如果你有字符串使用StringWriter

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

  using(JsonWriter textWriter = new JsonTextWriter(sw))
  {
     var serializer = new JsonSerializer();
     serializer.Serialize(textWriter, yourObject);
  }
Run Code Online (Sandbox Code Playgroud)


ren*_*ene 5

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

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;
        }
    }
Run Code Online (Sandbox Code Playgroud)