c# - JSON object does not serialize for huge data -


i trying serialize data in json. face below exception.

outofmemoryexception unhandled user code.
exception of type 'system.outofmemoryexception' occurred in newtonsoft.json.dll not handled in user code

below defined code:

main controller:

public class trackingcontroller : baseangularcontroller {     var lstdetails = _services.gettrackingdetailsbyawbids(awbids, awbtype);     if (lstdetails != null)     {         return angularjson(lstdetails);     } } 

base controller:

public abstract class baseangularcontroller : controller {     public angularjsonresult<t> angularjson<t>(t model)     {         return new angularjsonresult<t>() { data = model };     } } 

angular json result class:

public class angularjsonresult<t> :angularjsonresult {     public new t data     {         { return (t)base.data; }         set { base.data = value; }     } } 

json result class:

public class angularjsonresult : jsonresult {     public override void executeresult(controllercontext context)     {         douninterestingbaseclassstuff(context);          serializedata(context.httpcontext.response);     }      private void douninterestingbaseclassstuff(controllercontext context)     {         if (context == null)         {             throw new argumentnullexception("context");         }          var response = context.httpcontext.response;         response.contenttype = string.isnullorempty(contenttype) ? "application/json" : contenttype;          if (contentencoding != null)         {             response.contentencoding = contentencoding;         }     }      protected virtual void serializedata(httpresponsebase response)     {         if (errormessages.any())         {             data = new             {                 errormessage = string.join("\n", errormessages),                 errormessages = errormessages.toarray()             };              response.statuscode = 400;         }          if (data == null) return;          response.write(data.tojson());     } } 

serializing object json:

public static class jsonextensions {     public static string tojson<t>(this t obj, bool includenull = true)     {         var settings = new jsonserializersettings         {             contractresolver = new camelcasepropertynamescontractresolver(),             converters = new jsonconverter[] { new stringenumconverter() },             referenceloophandling = newtonsoft.json.referenceloophandling.ignore,//newly added             //preservereferenceshandling =newtonsoft.json.preservereferenceshandling.objects,             nullvaluehandling = includenull ? nullvaluehandling.include : nullvaluehandling.ignore         };         return jsonconvert.serializeobject(obj, settings);     } } 

here defined angularjson method passing object , override executeresult method converting object json.

so serializedata method passing response , converting objet in json, data.tojson()

please let me know suggestions.

your problem serializing huge data string in memory on server, writing entire string httpresponsebase (which buffers default), , running out of memory somewhere in process, possibly exceeding maximum c# string length.

one way reduce memory use serialize directly httpresponsebase.outputstream using jsonserializer.serialize(). avoids intermediate string representation.

you may need set httpresponsebase.buffer = false, , if so, follow advice given in unbuffered output slow , wrap output stream in bufferedstream.

the following extension method can used this:

public static class httpresponsebaseextensions {     public static void writejson<t>(this httpresponsebase response, t obj, bool useresponsebuffering = true, bool includenull = true)     {         var contentencoding = response.contentencoding ?? encoding.utf8;         if (!useresponsebuffering)         {             response.buffer = false;              // use bufferedstream suggested in //https://stackoverflow.com/questions/26010915/unbuffered-output-very-slow             var bufferedstream = new bufferedstream(response.outputstream, 256 * 1024);             bufferedstream.writejson(obj, contentencoding, includenull);             bufferedstream.flush();         }         else         {             response.outputstream.writejson(obj, contentencoding, includenull);         }     }      static void writejson<t>(this stream stream, t obj, encoding contentencoding, bool includenull)     {         var settings = new jsonserializersettings         {             contractresolver = new camelcasepropertynamescontractresolver(),             converters = new jsonconverter[] { new stringenumconverter() },             referenceloophandling = newtonsoft.json.referenceloophandling.ignore,//newly added             //preservereferenceshandling =newtonsoft.json.preservereferenceshandling.objects,             nullvaluehandling = includenull ? nullvaluehandling.include : nullvaluehandling.ignore         };         var serializer = jsonserializer.createdefault(settings);         var textwriter = new streamwriter(stream, contentencoding);         serializer.serialize(textwriter, obj);         textwriter.flush();     } } 

then use extension method in place of response.write(data.tojson());


Comments