-2

On only really large collections the following line throws an OutofMemroyException at mscorlib.dll at server level

HttpResponseMessage  response;
response.Content= new StringContent(JsonConvert.SerializeObject(results), 
system.Encoding.UTF8, "text/json");

However the following method serializing the same object dose not produces this error

Var serializer= new System.Web.Script.Serilaization.JavascriptSerializer() 
{MaxJsonLength = int.MaxValue};
response.Content= new StringContent(serializer.Serialize(results), 
system.Encoding.UTF8, "text/json")

However with second method the client throws the error:

Cannot deserialize the current json array because the the type requires a json object

So I am hoping either solve the memory issue with the first method or figure out why the second method can bot be deserialized like the first method

Thanks

John Sheridan
  • 83
  • 1
  • 2
  • 10
  • Any more detail you can give about the client side code? My guess would be that, if the first method is running out of memory, that the second might be returning a truncated JSON string which the client is failing to deserialize because it isn't complete. – dezfowler Jul 10 '19 at 15:19
  • The client side code which work fine with JsonConvert.SerializeObject method and smaller datasets: `var response = await GetData(client, query);` `var resultSet = await response.Content.ReadAsAsync();` `private async Task GetData(HttpClient client, DataQuery query)` `{` `var response = await client.PostAsJsonAsync(Settings.Default.Uri + @"/cmd", query);` `response.EnsureSuccessStatusCode();` `return response;` `}` – John Sheridan Jul 11 '19 at 01:49

1 Answers1

-1

With large amounts of data you want to be streaming it to the client so you're not trying to hold the whole thing in memory on the server which is what is happening in your examples.

Here's a good post on how you can use JsonTextWriter and JsonSerializer to write directly to the response stream which will minimise your memory footprint.

http://www.bizcoder.com/returning-raw-json-content-from-asp-net-web-api

dezfowler
  • 1,238
  • 10
  • 20