c# - JSON反序列化,错误: null to value type,如何知道导致错误的确切属性?

标签 c# .net json-deserialization javascriptserializer

在我的 C# 代码中,我尝试反序列化具有 100 多个属性(复杂、原始、派生)的 JSON,但我收到错误 Cannot convert null to a value type.

虽然我最终通过手动故障排除知道是哪个属性导致了问题。

但是有什么方法可以让我简单地知道 JSON 或 Result_TYPE property or properties (一口气)导致问题?

我尝试查看 detail window异常(exception),但我只能知道 datatype .就我而言,它是 null试图转换为 boolean ., 但未找到属性名称。

例如:我的JSON

  {
      "customerData": 
      {
        //... other json data

        "someClass":{
            "someClassProp1":"prop1Value",
            "someClassProp2":"prop2Value"
           },
        "isExistData":null,
        "someOtherClass":null

        //... some other json data
      }
  }

Result_TYPE 是:

Public class CustomerData
{
    // Other properties

    public SomeClass someClass:
    public bool isExistData;    
    public SomeOtherClass someOtherClass:

    // some Other properties
}

I'm using JavaScriptSerializer().Deserialize<T>(jsonString);

在上面的例子中:我怎么知道属性 isExistData会导致反序列化错误,因为属性类型是boolean传入数据是 null . [当然除了手动调试,因为可能有 100 多个属性]

有人知道找到确切属性的更好方法吗?

最佳答案

如果您不介意使用其他序列化器,那么只需使用 JSON .NET,它允许您在反序列化时遇到错误时运行自定义代码:

var errors = new List<string>();
var data = JsonConvert.DeserializeObject<CustomerData>(jsonString,
    new JsonSerializerSettings
    {
        NullValueHandling = NullValueHandling.Include,
        Error = delegate (object sender, Newtonsoft.Json.Serialization.ErrorEventArgs earg)
         {
             errors.Add(earg.ErrorContext.Member.ToString());
             earg.ErrorContext.Handled = true;
         }
    });

在错误中,您将拥有所有有问题的属性。当然,默认情况下 JSON .NET 不会在 null 属性上失败,这就是我设置 JsonSerializerSettings 的 NullValueHandling 属性的原因。您可以在文档中阅读更多信息:http://www.newtonsoft.com/json/help/html/SerializationErrorHandling.htm

如果出于任何原因您必须继续使用 JavaScriptSerializer,那么只需将您的对象反序列化为动态对象 (Deserialize JSON into C# dynamic object?),然后检查值类型的任何属性是否没有空值:

foreach (var property in typeof(CustomerData).GetProperties().Where(p => p.PropertyType.IsValueType))
{
    if (dynamicsData[property.Name] == null)
    {
        Console.WriteLine($"This is problematic property: {property.Name}");
    }
}

关于c# - JSON反序列化,错误: null to value type,如何知道导致错误的确切属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43343458/

相关文章:

C# ArrayList 调用构造函数类

c# - 使用 CaSTLe Windsor 为单个接口(interface)注册多个组件

c# - SignalR 中打开的连接列表?

.net - Unity 中无属性的 Setter/属性注入(inject)

java - 如何使用 Jackson 的本地化小数点分隔符反序列化浮点值

java - 如何使用 Jackson 反序列化混合类型的匿名数组

c# - 每行运行 Lua 脚本

c# -/*!*/在 C# 中是什么意思?

.net - 点网核心vs点网标准

java - Jackson解析错误: exception org. codehaus.jackson.map.exc.UnrecognizedPropertyException:无法识别的字段 "Results"