使用Json.Net序列化对象会导致内存不足异常 [英] Serializing an object using Json.Net causes Out of Memory exception
问题描述
免责声明:我确实经历了此处提供的大多数解决方案,但大多数人都在谈论反序列化时的OOM异常.
Disclaimer: I did went through most of the solution provided here but most of them were talking about OOM exception while Deserialization.
我正在尝试使用Json.Net将一个对象(它是一棵树)序列化为Json.一切都适用于小对象,但是当我尝试使用大对象时会出现OOM异常.因为它适用于相同数据类型的较小对象,所以我假设没有循环引用(我确实检查了它的数据结构). 是否可以将对象转换为流(这是Windows Store应用程序)并使用该流生成Json?
I am trying to serialize an object( it's a Tree) into Json using Json.Net. Everything works fine for small objects but i get OOM exception when i try it with large objects. As it works with smaller object of same datatype i am assuming there is no circular reference (I did inspect my data structure for it). Is there a way where i can convert my object into stream ( this is a Windows Store app ) and generate the Json using that stream ?
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 Store应用程序dll中没有该代码.
In order to convert my object into stream, the code i found out was using a BinaryFormatter which is not available in Windows store app dll's.
推荐答案
这是由于您要序列化的记录数量过多,这会占用大量内存.我发现此错误的解决方案是使用StreamWriter(JsonWriter或TextWriter)直接写入文档.
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).
如果您有对象,请使用TextWrite
If you have Object use TextWrite
using (TextWriter textWriter = File.CreateText("LocalJsonFile.json"))
{
var serializer = new JsonSerializer();
serializer.Serialize(textWriter , yourObject);
}
如果您有字符串,请使用StringWriter
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);
}
这篇关于使用Json.Net序列化对象会导致内存不足异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!