简体   繁体   中英

Debugging when deserializing a Json file with JsonConvert

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.

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
        get { return TraceLevel.Verbose; }
    }

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

And set it at deserialization

JsonConvert.DeserializeObject(myJson, new JsonSerializerSettings { TraceWriter = new ConsoleTraceWriter() });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM