c# - 处理json反序列化错误

标签 c# .net json.net json-deserialization

如何从 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/

相关文章:

c# - OleDbConnection 仅当工作簿也在 Excel 中打开时才查找单元格值

c# - ApiController int 或 string URI 参数的相同路由

asp.net-web-api - 访问 ASP.NET Web API 中的默认 JSON.NET 序列化程序

c# - 使用 JSON.NET 反序列化 JSON 字符串

c# - 在 C# 的代码隐藏中编写 SQLdatasource 以使用代码隐藏值

c# - 跨所有 View 模型处理 token 过期事件的策略

.net - AssemblyInfo.cs 中的 GuidAttribute 错误

c# - 在 C# .NET 中,如何读取具有基于 ascii 的专有编码的文本文件

c# - LINQ to SQL 添加 CASE 语句,然后原始字段未找到

c# - 反序列化 KeyValuePair<string, string> Json.Net