I use the following code to serialize JSON
JsonSerializerSettings settings = new JsonSerializerSettings()
{
Culture = CultureInfo.InvariantCulture,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
MaxDepth = 10
};
string serializationResult = JsonConvert.SerializeObject(currentObject, settings);
But i have found that if currentObject contains not serializable items it will throw Exception (for example a reference to dirty a DataContext). I have no control over currentObject because the actual code is part of a logging utility, and so 'currentObject' could be everything the utility user submitted to utility. I would like to be able to serialize 'currentObject' as much as i can, avoiding problematic properties if there are any.
So i modified the code in the following way :
try
{
JsonSerializerSettings settings = new JsonSerializerSettings()
{
Culture = CultureInfo.InvariantCulture,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
MaxDepth = 10,
Error = delegate (object sender, ErrorEventArgs args)
{
args.ErrorContext.Handled = true;
}
};
string serializationResult = JsonConvert.SerializeObject(currentObject, settings);
return serializationResult;
}
catch ( Exception err)
{
return string.Empty;
}
I test it again passing a 'currentObject' in which a property is a dirty DataConetxt, and now the serialization process never end. Seems like it keep looping on the error hanlder. After an huge amount of times (few minutes) i finally get a serialization error :
System.NotSupportedException: 'Specified method is not supported.'
at System.Web.HttpResponseStream.get_Length()
at GetLength(Object )
at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)
Is not clear to me what i am missin and how to handle such situation in which a property of object to serialize may be not serializable. Is my logic correct but the prolem is that DataContext is huge to serialize (and if so i have to try to filter out such situation)?
Or i mistakenly impelemented the error handling?