简体   繁体   English

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

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

In my C# code, I'm trying to deserialize a JSON with 100s of properties (complex, primitive, derived) and I'm getting an error Cannot convert null to a value type. 在我的C#代码中,我正在尝试使用100个属性 (复杂,原始,派生)反序列化JSON,并且我收到错误Cannot convert null to a value type.

Though I finally knew which property is causing a problem by manual troubleshooting. 虽然我终于通过手动故障排除知道哪个属性导致了问题。

But is there any way by which I can simply know the JSON or Result_TYPE property or properties ( in one go), causing the issue ? 但有什么方法可以简单地知道JSON或Result_TYPE property or properties (一次性),导致问题?

I tried looking into detail window of Exception but I could only know the datatype . 我试着查看Exception的detail window ,但我只能知道datatype In my case, it was null trying to convert to boolean ., but not found the property name. 在我的情况下,它尝试转换为boolean null ,但没有找到属性名称。

For example: My JSON 例如:我的JSON

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

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

        //... some other json data
      }
  }

and Result_TYPE is : 和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); 我正在使用JavaScriptSerializer().Deserialize<T>(jsonString);

In above example: How would I know that property isExistData will lead the deserialization error, because property type is boolean and incoming data is null . 在上面的示例中:我如何知道属性isExistData将导致反序列化错误,因为属性类型是boolean ,传入数据是null [ofcourse apart from manual debugging as there might be 100s of properties] [除了手动调试之外,因为可能有100多个属性]

anyone, if knows the better way to locate the exact property? 任何人,如果知道更好的方法来找到确切的财产?

If you don't mind using other serializer, then simply use JSON .NET, it allows you to runa a custom code when you have an error while deserializing: 如果您不介意使用其他序列化程序,那么只需使用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;
         }
    });

in errors you will have all problematic properties. 如果出现错误,您将拥有所有有问题的属性。 Of course JSON .NET by default will not fail on null properties, that's why I've set the NullValueHandling property of JsonSerializerSettings. 当然,JSON .NET默认情况下不会在null属性上失败,这就是我设置JsonSerializerSettings的NullValueHandling属性的原因。 You can read more in documentation: http://www.newtonsoft.com/json/help/html/SerializationErrorHandling.htm 您可以在文档中阅读更多内容: http//www.newtonsoft.com/json/help/html/SerializationErrorHandling.htm

If by any reasons you have to stay with JavaScriptSerializer, then simply deserialize oyour object to a dynamics object ( Deserialize JSON into C# dynamic object? ) and then check if any properties that are of value type don't have null value: 如果由于任何原因你必须继续使用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