private readonly JsonSerializerSettings settings = new JsonSerializerSettings {
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
ContractResolver = new DefaultContractResolver {
NamingStrategy = new CamelCaseNamingStrategy()
}
};
Protect against serialization of the entire world. Ex. Microsoft Extension Logging might log properties of these types:
settings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
settings.Converters.Add(new JsonToStringConverter(typeof(System.Reflection.MemberInfo)));
settings.Converters.Add(new JsonToStringConverter(typeof(System.Reflection.Assembly)));
settings.Converters.Add(new JsonToStringConverter(typeof(System.Reflection.Module)));
settings.Error = (sender, args) =>
{
args.ErrorContext.Handled = true; // Ignore Properties that throws Exceptions
};
/// <summary>
/// JSON converter that just calls ToString on the target value (when non-null).
/// This is configured as the converter for types that will otherwise spew a lot of irrelevant JSON
/// into logs.
/// </summary>
internal sealed class ToStringJsonConverter : JsonConverter
{
private readonly System.Type _type;
/// <inheritdoc />
public override bool CanRead => false;
public ToStringJsonConverter(System.Type type) =>
_type = type;
/// <inheritdoc />
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value is null)
{
writer.WriteNull();
}
else
{
writer.WriteValue(value.ToString());
}
}
/// <inheritdoc />
public override object ReadJson(JsonReader reader, System.Type objectType, object existingValue, JsonSerializer serializer) =>
throw new NotSupportedException("Only serialization is supported");
/// <inheritdoc />
public override bool CanConvert(System.Type objectType) =>
_type.IsAssignableFrom(objectType);
}