MaxJsonLength Error when decoding jsonstring using System.Web.Helpers.Json.Decode

Sandeep Reddy Pinniti 1 Reputation point
2022-03-01T20:50:54.723+00:00

Hi Team,

I got an error when decoding jsonstring using System.Web.Helpers.Json.Decode. How to set maxJsonLength while using System.Web.Helpers.Json.Decode method.

Errors: System.ArgumentException -- Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property. Parameter name: input at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit) at System.Web.Helpers.Json.Decode(String value)

Thanks in advance

Developer technologies ASP.NET Other
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Yijing Sun-MSFT 7,096 Reputation points
    2022-03-02T02:41:42.873+00:00

    Hi @Sandeep Reddy Pinniti ,
    I suggest you could create System.Web.Script.Serialization.JavaScriptSerializer, which allows access to the MaxJsonLength property:

    JavaScriptSerializer ser = new JavaScriptSerializer();  
    ser.MaxJsonLength = Int32.MaxValue;  
    var jsonArtikel = ser.Serialize(Model);  
    

    Best regards,
    Yijing Sun


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our  documentation  to enable e-mail notifications if you want to receive the related email notification for this thread.


  2. Yijing Sun-MSFT 7,096 Reputation points
    2022-03-02T09:18:39.28+00:00

    Hi @Sandeep Reddy Pinniti ,
    The following is a tested and working DynamicJsonObjectFormatter. It has a static method dynamic DynamicJsonObjectFormatter.Decode(string json) that duplicates System.Web.Helpers.Json.Decode, but gives you control of the max length:

    public class DynamicJsonObjectFormatter : BufferedMediaTypeFormatter  
    {  
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);  
      
        public static dynamic Decode(string json, int maxLength=0)  
        {  
            try  
            {  
                if (string.IsNullOrEmpty(json))  
                    return null;  
                var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();  
                if( maxLength>0) {  
                    serializer.MaxJsonLength = maxLength;  
                }  
                var deserialized = serializer.DeserializeObject(json);  
                if (deserialized != null)  
                {  
                    var dictValues = deserialized as IDictionary<string, object>;  
                    if (dictValues != null)  
                        return new DynamicJsonObject(dictValues);  
                    var arrayValues = deserialized as object[];  
                    if (arrayValues != null)  
                    {  
                        return new DynamicJsonArray(arrayValues);  
                    }  
                }  
                log.Error("Internal: Attempt to deserialize unrecognized JSON string as DynamicJsonObject");  
            }  
            catch (Exception ex)  
            {  
                log.Error("Internal: exception deserializing JSON", ex);  
            }  
            return null;  
        }  
        override public object ReadFromStream(Type type, System.IO.Stream readStream, System.Net.Http.HttpContent content, IFormatterLogger formatterLogger)  
        {  
            System.IO.StreamReader strdr = null;  
            try  
            {  
                strdr = new System.IO.StreamReader(readStream);  
                string json = strdr.ReadToEnd();  
                int maxLength = 33554432; //Int32.MaxValue;  
                return Decode(json, maxLength);  
            }  
            catch (Exception ex)  
            {  
                log.Error("Internal: exception deserializing JSON", ex);  
            }  
            finally  
            {  
                if (strdr != null)  
                {  
                    strdr.Dispose();  
                }  
            }  
            return null;  
        }  
      
        public DynamicJsonObjectFormatter()  
        {  
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));  
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/json"));  
            //SupportedEncodings.Add(new UTF8Encoding(false, true));  
        }  
      
        public override bool CanReadType(Type type)  
        {  
            return (type == typeof(DynamicJsonObject)) || (type == typeof(DynamicJsonArray));  
        }  
      
        public override bool CanWriteType(Type type)  
        {  
            return false;  
        }  
      
    }  
    

    (Note: the strdr.ReadToEnd() may also give you an issue with large files. It's size limit can be controlled with

    <system.web>  
        <httpRuntime targetFramework="4.6.2" maxRequestLength="200000" />  
        <!-- maxRequestLength is in KB, not B -->  
    </system.web>  
    

    in your Web.config file.
    Best regards,
    Yijing Sun


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our  documentation  to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.