1

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?

https://dotnetfiddle.net/ewio89

stackMeUp
  • 161
  • 7
  • "non-fatal" exceptions do not exist. This looks like the exception is catched but then somehow logged. Without the code it's difficult to understand what happens here. It would help, if you could provide the relevant code. – Christoph Lütjen Sep 23 '22 at 13:36
  • You can debug library ~ https://stackoverflow.com/q/44383026/1462295 or decompile .net dll is simple. Second, explore writing a custom serializer ~ https://stackoverflow.com/a/30083923/1462295 – BurnsBA Sep 23 '22 at 13:37
  • 2
    In order to implement [custom exception handling](https://www.newtonsoft.com/json/help/html/SerializationErrorHandling.htm), Json.NET catches and rethrows exceptions at every level of serialization. Eventually the exception will "filter out" to the call of `JsonConvert` and you will be able to examine. Or you can add a [custom error handler](https://www.newtonsoft.com/json/help/html/SerializationErrorHandling.htm) to watch what happens for each catch/rethrow, if you prefer. See e.g. [Ignore parsing errors during JSON.NET data parsing](https://stackoverflow.com/q/26107656/3744182). – dbc Sep 23 '22 at 16:25
  • But what exactly is your problem? Is the `JsonSerializationException` getting swallowed internally and never thrown out to the caller? – dbc Sep 23 '22 at 16:27
  • @dbc, thank you for the links. That seems to do the trick. Without specifying/setting up error handling (as you suggested), errors are thrown, but nothing breaks, which is bad as you keep on going assuming everything is fine, while it is in fact not. – stackMeUp Sep 26 '22 at 07:24
  • @dbc, I have tried without success. I updated my post with actual code. Would you mind having a look at it? Thanks – stackMeUp Sep 26 '22 at 15:35
  • Can you [edit] your question to share a [mcve], specifically code + JSON that reproduce your problem? – dbc Sep 26 '22 at 16:41
  • @dbc, I created an MRE [here](https://dotnetfiddle.net/ewio89) based on a past example you compiled for me ages ago using Fiddler. I am however unable to set breakpoints to debug. F9 is not working. Any idea why not? – stackMeUp Sep 27 '22 at 15:32
  • @stackMeUp What do you nedd a custom converter for? I can deserialize your json without customconverter and errors. – Serge Sep 27 '22 at 15:58
  • @stackMeUp - I still don't see your problem. Your MRE sets `args.ErrorContext.Handled = true`, so deserialization proceeds and returns `null` because the JSON value type (an array) does not match the contract for `ConvolutedObject` which requires an object: https://dotnetfiddle.net/qVl593... – dbc Sep 27 '22 at 17:27
  • @stackMeUp: ... On the other hand if I remove `Handled = true` then the exception is eventually then out to the caller, see https://dotnetfiddle.net/u30IQ9. You wrote *Using a try/catch won't work as the exception is internal to the dll and the deserialization end up running successfully to completion.* but I just can't see that happening. The exception ***is*** thrown out and serialization does not end up running successfully to completion. – dbc Sep 27 '22 at 17:28
  • What is your real problem here anyway? Is it that you have a JSON array that you are not deserializing to a collection? JSON arrays need to be deserialized to .NET collections as explained in [the docs](https://www.newtonsoft.com/json/help/html/DeserializeCollection.htm). So you needed to do `JsonConvert.DeserializeObject>(...)`. – dbc Sep 27 '22 at 17:31
  • @dbc, this is just an MRE. The full source code is far too big to copy paste in there. I do need to deserialise into an object as the reconstructed object will be an object. The custom deserialisation is also needed as it is not possible to deserialise the given json input straight into that object. For some reasons, I do not have errors popping (irrelevant of the way args.ErrorContext.Handled is set), but I am working on an MRE that will show that. Bare with me. Thanks a lot for your help. – stackMeUp Sep 28 '22 at 08:02
  • @dbc, I do not manage to create an MRE that emphasizes the problem, grrrr. The original has far too many layers to be able to share it :-( Layers composed of objects that are composed of objects that are composed of objects, etc. (ie. the Json files to deserialise have many layers, hence the reference to "ConvolutedObject"). The problem must have to do with the custom deserializer. Maybe that is what is absorbing the errors. Maybe I should be defining the setting of deserializer at the top level. I'll keep on trying do create a good MRE, but it is not easy. Thanks again – stackMeUp Sep 28 '22 at 09:11

0 Answers0