Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Debugging when deserializing a Json file with JsonConvert

Tags:

c#

json.net

Is there a way to "debug a Json file" at deserialisation using JsonConvert?
It would be very useful if the line (or group of lines) of the Json file being processed could be printed as a debug option.
Otherwise, when the deserialisation of a Json file into an object fails, it can be very difficult to figure out what is wrong with that file.

like image 535
stackMeUp Avatar asked Aug 01 '26 02:08

stackMeUp


1 Answers

You can implement a custom TraceWriter that logs to console as deserialization goes on, like this. Of course you could also wrap it into a log4net log entry or just do whatever you like.:

public class ConsoleTraceWriter : ITraceWriter
{    
    public TraceLevel LevelFilter
    {
        // trace all messages (Verbose and above)
        get { return TraceLevel.Verbose; }
    }

    public void Trace(TraceLevel level, string message, Exception ex)
    {
        if (ex != null) {
            Console.WriteLine(level.ToString() + ": " + message + " Ex: " + ex.Message);
        } else {
            Console.WriteLine(level.ToString() + ": " + message);
        }
    }
}

And set it at deserialization

JsonConvert.DeserializeObject(myJson, new JsonSerializerSettings { TraceWriter = new ConsoleTraceWriter() });
like image 166
Dominik Avatar answered Aug 02 '26 18:08

Dominik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!