0

I am retrieving JSON but due to its limited length (2147483644), I am getting this error.

How can I catch this error?

Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.

This is how I am coding right now.

[HttpGet]
        public JsonResult GetSearchData(string filter)
        { 
            IRemediationService svc = new RemediationService();
            var data = svc.SearchData(filter);
            try{
              return Json(data, JsonRequestBehavior.AllowGet);
            }catch(Exception e){
              return "Error";
            }

    }
lostpacket
  • 1,383
  • 8
  • 26
  • 38

1 Answers1

2

In MVC 4 you can do:

protected override JsonResult GetSearchData(string filter)
{
    IRemediationService svc = new RemediationService();
    var data = svc.SearchData(filter);
    try
    {
        return new JsonResult()
            {
                Data = data,
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                MaxJsonLength = Int32.MaxValue
            };
    }
    catch (Exception e)
    {
        return "Error";
    }
}

You could check data and trim your object down.

If not maybe you can just pass it back as a string...

protected override ActionResult GetSearchData(string filter)
{
    IRemediationService svc = new RemediationService();
    var data = svc.SearchData(filter);
    try
    {
        return Content(data.ToString());
    }
    catch (Exception e)
    {
        return "Error";
    }
}
Faraday
  • 2,904
  • 3
  • 23
  • 46
  • Thanks.Is there any limit on the length of string being sent back ? – lostpacket Oct 07 '13 at 22:36
  • I guess that would vary by client. But I'm not sure. I've hit OOM exceptions before I've hit the max length. How big is your data!?! lol, perhaps you need to do a daily drop or something ;-) – Faraday Oct 07 '13 at 22:41
  • It varies. In JSON, I can say between {'Time': 1381186243 , 'Value' : 123.4} times 1000 or 5000 or even higher if the user is asking for wider time range or if a lot of values are collected in short period of time. – lostpacket Oct 07 '13 at 22:52
  • Event at double that length you could have 21474836 of them using the first approach `MaxJsonLength = Int32.MaxValue` – Faraday Oct 07 '13 at 22:56
  • Ok.Let me clear. So I could have any JSON object times 21474836 as the number of JSON objects I can send back to the browser? – lostpacket Oct 07 '13 at 22:59
  • If you explicitly set the length to Int32.MaxValue then you can have 2,147,483,647 characters. Try it out and see, some back to me if you have any issues. – Faraday Oct 07 '13 at 23:04