Click or drag to resize
Json.NETDebugging with Serialization Tracing
 

The Json.NET serializer supports logging and debugging using the ITraceWriter interface. By assigning a trace writer you can capture serialization messages and errors and debug what happens inside the Json.NET serializer when serializing and deserializing JSON.

ITraceWriter

A trace writer can be assigned using properties on JsonSerializerSettings or JsonSerializer.

Debugging serialization using MemoryTraceWriter
 1Staff staff = new Staff();
 2staff.Name = "Arnie Admin";
 3staff.Roles = new List<string> { "Administrator" };
 4staff.StartDate = new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc);
 5
 6ITraceWriter traceWriter = new MemoryTraceWriter();
 7
 8JsonConvert.SerializeObject(
 9    staff,
10    new JsonSerializerSettings { TraceWriter = traceWriter, Converters = { new JavaScriptDateTimeConverter() } });
11
12Console.WriteLine(traceWriter);
13// 2012-11-11T12:08:42.761 Info Started serializing Newtonsoft.Json.Tests.Serialization.Staff. Path ''.
14// 2012-11-11T12:08:42.785 Info Started serializing System.DateTime with converter Newtonsoft.Json.Converters.JavaScriptDateTimeConverter. Path 'StartDate'.
15// 2012-11-11T12:08:42.791 Info Finished serializing System.DateTime with converter Newtonsoft.Json.Converters.JavaScriptDateTimeConverter. Path 'StartDate'.
16// 2012-11-11T12:08:42.797 Info Started serializing System.Collections.Generic.List`1[System.String]. Path 'Roles'.
17// 2012-11-11T12:08:42.798 Info Finished serializing System.Collections.Generic.List`1[System.String]. Path 'Roles'.
18// 2012-11-11T12:08:42.799 Info Finished serializing Newtonsoft.Json.Tests.Serialization.Staff. Path ''.
19// 2013-05-18T21:38:11.255 Verbose Serialized JSON: 
20// {
21//   "Name": "Arnie Admin",
22//   "StartDate": new Date(
23//     976623132000
24//   ),
25//   "Roles": [
26//     "Administrator"
27//   ]
28// }

Json.NET has two implementations of ITraceWriter: MemoryTraceWriter, which keeps messages in memory for simple debugging, like the example above, and DiagnosticsTraceWriter, which writes messages to any System.Diagnostics.TraceListeners your application is using.

Custom ITraceWriter

To write messages using your existing logging framework, just implement a custom version of ITraceWriter.

Custom NLog TraceWriter
 1public class NLogTraceWriter : ITraceWriter
 2{
 3    private static readonly Logger Logger = LogManager.GetLogger("NLogTraceWriter");
 4
 5    public TraceLevel LevelFilter
 6    {
 7        // trace all messages. nlog can handle filtering
 8        get { return TraceLevel.Verbose; }
 9    }
10
11    public void Trace(TraceLevel level, string message, Exception ex)
12    {
13        LogEventInfo logEvent = new LogEventInfo
14        {
15            Message = message,
16            Level = GetLogLevel(level),
17            Exception = ex
18        };
19
20        // log Json.NET message to NLog
21        Logger.Log(logEvent);
22    }
23
24    private LogLevel GetLogLevel(TraceLevel level)
25    {
26        switch (level)
27        {
28            case TraceLevel.Error:
29                return LogLevel.Error;
30            case TraceLevel.Warning:
31                return LogLevel.Warn;
32            case TraceLevel.Info:
33                return LogLevel.Info;
34            case TraceLevel.Off:
35                return LogLevel.Off;
36            default:
37                return LogLevel.Trace;
38        }
39    }
40}
See Also