3

Recently discovered that existing serialization code fails when the object to convert is too large. I know how to increase the maximum length in .NET's JavascriptSerializer. But how do I do the same thing in JsonConvert.SerializeObject?

References to web.config setting:

<jsonSerialization maxJsonLength="50000000"/>

Say that it is only respected by WCF. We aren't using WCF. This is a simple .NET library that requires serialization of objects.

The relevant code is:

        public static string Serialize(object value)
        {
            return JsonConvert.SerializeObject(value, SerializerSettings);
        }

This is how I create the settings:

        private static JsonSerializerSettings SerializerSettings
        {
            get
            {
                var settings = new JsonSerializerSettings();
                settings.Converters.Add(new StringEnumConverter());
                settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                settings.NullValueHandling = NullValueHandling.Ignore;
                return settings;
            }
        }

I don't see a property I need in JsonSerializerSettings. My object is multilayered but mostly of string types. I convert an uploaded file and store it as a string. The size of that file is the element that I am changing when I see the failire.

Unfortunately the library I am using doesn't log so I can't find the exact error. But the code works with smaller files (<150KB) and fails with larger ones >500KB.

Shawn Melton
  • 41
  • 1
  • 1
  • 3
  • 6
    Json.NET doesn't have a maximum string length built into `JsonConvert.SerializeObject`. It will keep serializing until you run out of memory. Perhaps you're running into the [Max effective string length](https://stackoverflow.com/a/140749) on your computer. Are you running in 32-bit mode or 64? Do you really need to serialize to an intermediate `string` or could you do a streaming serialization to your final destination? – dbc Jul 10 '19 at 19:42
  • No, its wrong its failing. For below Maxchoicecount which gets converted to scientific notation without retaining original format. string json = "[{\"MaxChoiceCount\": 79228162514264337593543950335.0,\"MinChoiceCount\": 0.0,\"HelpText\": \"Input\"}]"; dynamic json2 = JsonConvert.DeserializeObject(json); – Madhusudhan V Indian Dec 08 '21 at 14:09

0 Answers0