【发布时间】:2014-09-30 19:15:36
【问题描述】:
免责声明:我确实经历了此处提供的大部分解决方案,但其中大多数都在谈论反序列化时的 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;
}
}
为了将我的对象转换为流,我发现的代码使用了 Windows 商店应用程序 dll 中不可用的 BinaryFormatter。
【问题讨论】:
-
尝试将
JsonSerializer与StreamReader结合使用,如here 所述。 -
我确实查看了代码,这让我想到了一个问题:有没有办法可以将我的对象转换为流(这是一个 Windows 应用商店应用程序)?
-
这就是序列化程序所做的。它获取所有属性并将它们转换为字符串。在这种情况下,它可以将它们直接存入流(例如文件流)而不是返回字符串,这样它们就不会位于内存中。
-
好吧,这行得通,我有 TraceListner,它在每次序列化和反序列化时在内部创建字符串。
-
也许 Nate Diamond 可以添加一个答案,以便它可以被接受。也为我工作!
标签: c# serialization windows-store-apps json.net out-of-memory