我正在使用NLog,并且正在通过导线发送LogEventInfo
对象,我不拥有此对象,因此无法使用[JsonConverter(typeof(StringEnumConverter))]
装饰它,或者也许可以,但我不知道如何
我尝试了以下代码,但没有帮助
var strategy = new Newtonsoft.Json.Serialization.CamelCaseNamingStrategy();
var sec = new StringEnumConverter(strategy, false);
//TEMP Hard code serialization and message routing for just logs
LogEventInfo info = Newtonsoft.Json.JsonConvert.DeserializeObject<LogEventInfo>(msg.Body, sec);
没有人有运气让枚举反序列化并且枚举属于您不拥有的类吗?
这是消息:
{
"date":"2019-06-04 21:48:24.0753",
"level":"Error",
"message":"{\"ApplicationId\":1390760,\"AppStatus\":\"#PG2\",\"Status\":400,\"ErrorCode\": 1053 }",
"properties":"ResponseBody={\"ApplicationId\":1390760,\"AppStatus\":\"#PG2\",\"Status\":400,\"ErrorCode\": 1053 }|GroupId=392934|ApplicationId=1390760|Status=400",
"callsite":"HFD.Enterprise.Logging.Tests.LogTest.LoadTest",
"logger":"WebApiLog",
"machinename":"BRANDONHOSTVS"
}
这是一个例外:
Newtonsoft.Json.JsonSerializationException: Error converting value "Error" to type 'NLog.LogLevel'. Path 'level', line 1, position 72. ---> System.InvalidCastException: Invalid cast from 'System.String' to 'NLog.LogLevel'.
at System.Convert.DefaultToType(IConvertible value, Type targetType, IFormatProvider provider)
at System.String.System.IConvertible.ToType(Type type, IFormatProvider provider)
at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureType(JsonReader reader, Object value, CultureInfo culture, JsonContract contract, Type targetType)
--- End of inner exception stack trace ---
最佳答案
您的基本问题是LogEventInfo.Level
不是枚举,它是LogLevel
类,恰好实现了IConvertible
并具有一组全局静态标准值:
public sealed class LogLevel : IComparable, IEquatable<LogLevel>, IConvertible
{
/// <summary>
/// Gets all the available log levels (Trace, Debug, Info, Warn, Error, Fatal, Off).
/// </summary>
public static IEnumerable<LogLevel> AllLevels => allLevels;
添加
StringEnumConverter
不会帮助您(反)序列化此类属性。而且,NLog似乎没有为
TypeConverter
提供自定义的LogLevel
。如果我调用TypeDescriptor.GetConverter(typeof(LogLevel))
,则返回的值是默认转换器System.ComponentModel.TypeConverter
的实例,这意味着Json.NET无法将序列化的LogLevel
字符串值转换回LogLevel
实例。但是,您的JSON示例确实将
Level
表示为"level": "Error"
,因此发送系统必须一直在对JsonConverter
使用某种custom LogLevel
来对LogLevel.Name
进行序列化。我们可以很容易地重新创建这样的JsonConverter
,如下所示:public class LogLevelConverter : JsonConverter<LogLevel>
{
public override LogLevel ReadJson(JsonReader reader, Type objectType, LogLevel existingValue, bool hasExistingValue, JsonSerializer serializer)
{
switch (reader.MoveToContentAndAssert().TokenType)
{
case JsonToken.Null:
return null;
case JsonToken.String:
return LogLevel.FromString((string)reader.Value);
default:
throw new JsonSerializationException(string.Format("Unknown token {0}", reader.TokenType));
}
}
public override void WriteJson(JsonWriter writer, LogLevel value, JsonSerializer serializer)
{
var logLevel = (LogLevel)value;
writer.WriteValue(logLevel.Name);
}
}
public static partial class JsonExtensions
{
public static JsonReader MoveToContentAndAssert(this JsonReader reader)
{
if (reader == null)
throw new ArgumentNullException();
if (reader.TokenType == JsonToken.None) // Skip past beginning of stream.
reader.ReadAndAssert();
while (reader.TokenType == JsonToken.Comment) // Skip past comments.
reader.ReadAndAssert();
return reader;
}
public static JsonReader ReadAndAssert(this JsonReader reader)
{
if (reader == null)
throw new ArgumentNullException();
if (!reader.Read())
throw new JsonReaderException("Unexpected end of JSON stream.");
return reader;
}
}
然后按如下方式使用它:
var seq = new LogLevelConverter();
var info = Newtonsoft.Json.JsonConvert.DeserializeObject<LogEventInfo>(msg.Body, seq);
演示小提琴here。