Debugging when deserializing a Json file with JsonConvert

Viewed 588

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.

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() });
Related