When deserializing a Json File into an object using the NewtonSoft.Json converter, I see a lot of exceptions written to the console's output. The error is the following one (repeated many times over):
Exception thrown: 'Newtonsoft.Json.JsonSerializationException' in Newtonsoft.Json.dll
Is there a way to catch these exception so that I can fix the issue?
Using a try/catch won't work as the exception is internal to the dll and the deserialization end up running successfully to completion. Meaning, I do get the expected deserialised object with all the correct values.
One might say that there is nothing to worry about, but I would really like to understand where all these non-fatal exceptions come from and if they need to be addressed.
Maybe there is a way to override "JsonSerializationException" somehow?
Any tips or code example would be very welcome.
EDIT
It would appear that I have a bigger problem, so here is more background on what my code is actually doing:
// Here is the top layer call that calls my custom Converter
var MyConvolutedObject=
           JsonConvert.DeserializeObject<ConvolutedObjectType>(
                    File.ReadAllText(pathToSerializedObject), new MyCustomConverter());
Here is the actual converter. I tried to simplify as much as possible for readability. Please let me know if you need clarifications:
namespace MyNamespace
{
    public class MySerializationBinder : DefaultSerializationBinder
    {
        private string _context;
        public MySerializationBinder(string context)
        {
            _context = context;
        }
        public override Type BindToType(string assemblyName, string typeName)
        {
            // Some more subtitutions. I won't bore you with that.
            switch (typeName.ToLower())
            {
                case "bool":
                    return typeof(...);
                case "int":
                case "int32":
                    return typeof(...);
                default: return base.BindToType(assemblyName, typeName);
            }
        }
    }
    public class MyCustomConverter : JsonConverter
    {
        protected string ObjectFileConverter(string objectFile)
        {
            // This part does some text substitutions as the "serialized object" is not a perfect match
            // ......
            return objectFile;
        }
        public override bool CanConvert(Type objectType)
        {
            return typeof(ConvolutedObjectType).GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo());
        }
        static  List<string> errors = new List<string>();
        static readonly JsonSerializerSettings _jsonSettings = new JsonSerializerSettings
        {
            Error = delegate (object sender, ErrorEventArgs args)
            {
                errors.Add(args.ErrorContext.Error.Message);
                args.ErrorContext.Handled = true;
            },
            //Converters = ??,
            TypeNameHandling = TypeNameHandling.All,
            ObjectCreationHandling = ObjectCreationHandling.Replace,
            PreserveReferencesHandling = PreserveReferencesHandling.Objects,
            SerializationBinder = new MySerializationBinder("Context")
        };
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            JToken token = JToken.Load(reader);
            string adaptedObject = token.ToString();
            
            // Do some text substitution to obtain the correct object format so that it can get deserialized
            adaptedObject = ObjectFileConverter(adaptedObject);
            return JsonConvert.DeserializeObject<ConvolutedObjectType>(adaptedObject, _jsonSettings);
        }
        public override bool CanWrite
        {
            get { return false; }
        }
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }
    }
}
As you see, I am using a custom converter. Could it be why the exceptions are not actually raised?
>(...)`.
– dbc Sep 27 '22 at 17:31