如何从 JsonSerializer.Error 处理程序获取原始 json 字符串(传递给 JsonConvert.DeserializeObject 方法)?
public MyModel ParseFromJsonString(string jsonString)
{
var jsonSerializerSettings = new JsonSerializerSettings()
{
jsonSerializerSettings.Error = OnError;
}
return JsonConvert.DeserializeObject<MyModel>(jsonString, jsonSerializerSettings);
}
...
private void OnError(object sender, ErrorEventArgs errorEventArgs)
{
//How to get this from current place ?
string originalJsonString;
//in log record I want to mention incoming json string that was processed by deserialization
logger.Error("error: {0}, happened at deserialisation json: {1}", errorEventArgs.ErrorContext.Error.Message, originalJsonString);
//allows to continues deserializing, ignoring error and prevents throwing exception
errorEventArgs.ErrorContext.Handled = true;
}
errorEventArgs中没有这样的属性,然后我认为它应该在“sender”中,它是JsonSerializer的实例,它包含很多属性,但我也没有找到。 不明白,为什么像 json.net 这样酷的包没有包含这个。 String 是引用类型,因此应该可以在 errorEventArgs 中存储对同一字符串实例的引用,并且不会消耗额外的内存进行复制(在大 json 的情况下会降低性能)
最佳答案
通过将错误处理程序转换为 lambda,您可以在 C# 编译器的帮助下访问它。
public MyModel ParseFromJsonString(string jsonString)
{
var jsonSerializerSettings = new JsonSerializerSettings()
{
Error = (sender, errorEventArgs) =>
{
//You can use your "jsonString" here
}
};
return JsonConvert.DeserializeObject<MyModel>(jsonString, jsonSerializerSettings);
}
PS:它是如何工作的? C# Closures Explained , Closures In C#
关于c# - 处理json反序列化错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31793270/