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.