Serializing an object using Json.Net causes Out of Memory exception

后端 未结 2 1060
遇见更好的自我
遇见更好的自我 2020-12-17 22:47

Disclaimer: I did went through most of the solution provided here but most of them were talking about OOM exception while Deserialization.

I am trying to serialize a

相关标签:
2条回答
  • 2020-12-17 23:26

    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);
      }
    
    0 讨论(0)
  • Updated Code based on suggestions in the comments on the question, This works!

    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;
            }
        }
    
    0 讨论(0)
提交回复
热议问题