繁体   English   中英

JSON反序列化,错误:null到值类型,如何知道确切的属性导致错误?

[英]JSON deserialize , Error : null to value type, how to know exact property causing error?

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

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

但有什么方法可以简单地知道JSON或Result_TYPE property or properties (一次性),导致问题?

我试着查看Exception的detail window ,但我只能知道datatype 在我的情况下,它尝试转换为boolean null ,但没有找到属性名称。

例如:我的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
}

我正在使用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,那么只需将oyour对象反序列化为动态对象(将JSON反序列化为C#动态对象? ),然后检查是否有任何值类型的属性没有null值:

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}");
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM