0

How should handle System.OutOfMemoryException exception while parsing a large string which is coming as an API Response.

I am getting this exception while parsing a large string

Exception of type 'System.OutOfMemoryException' was thrown. System.OutOfMemoryException OutOfMemoryException System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
   at Newtonsoft.Json.Linq.JToken.SetLineInfo(IJsonLineInfo lineInfo, JsonLoadSettings settings)
   at Newtonsoft.Json.Linq.JContainer.ReadContentFrom(JsonReader r, JsonLoadSettings settings)

This is the simple code that I am running.

var jObject= JObject.Parse(responseString);
S7H
  • 1,421
  • 1
  • 22
  • 37
  • The exception seems to be rather clear. What is your question? – Klaus Gütter Apr 14 '22 at 11:14
  • How should I parse a large string that could cause this exception? – S7H Apr 14 '22 at 11:15
  • what version of Newtonsoft are you using? I've been having problems with 13 (crashing the whole server). So we went back to 12.0.3 and everything is ok again. [see this issue](https://github.com/JamesNK/Newtonsoft.Json/issues/2593) – JHBonarius Apr 14 '22 at 11:17
  • 2
    is this `responseString` originally a `Stream`? if yes, you might be interested to parse the stream directly, see [docs](https://www.newtonsoft.com/json/help/html/Performance.htm). – Bagus Tesa Apr 14 '22 at 11:17
  • How large is that string? Are your running as 64bit or 32bit app? – Klaus Gütter Apr 14 '22 at 11:17
  • 1
    Does this answer your question? [Out of memory exception while loading large json file from disk](https://stackoverflow.com/questions/39955399/out-of-memory-exception-while-loading-large-json-file-from-disk) – Martin Bartolomé Apr 14 '22 at 11:19

1 Answers1

0

You should use the StreamRreader class to parse some of the message at a time.

  • this could indeed help: please expand your answer with examples – JHBonarius Apr 14 '22 at 11:20
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Cristik Apr 14 '22 at 12:22