JSON deserialize , Error : null to value type, how to know exact property causing error?
Asked Answered
S

1

8

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.

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 ?

I tried looking into detail window of Exception but I could only know the datatype. In my case, it was null trying to convert to boolean., but not found the property name.

For example: My JSON

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

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

        //... some other json data
      }
  }

and Result_TYPE is :

Public class CustomerData
{
    // Other properties

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

    // some Other properties
}

I'm using 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. [ofcourse apart from manual debugging as there might be 100s of properties]

anyone, if knows the better way to locate the exact property?

Straus answered 11/4, 2017 at 10:31 Comment(5)
isExistData is a value type that can't be null...Ming
you could consider making the value types nullable...Ming
@DanielA.White : yeah I know that :), already solve my problem but curious to know is there any serializer/deserialzer which could locate at run time?Straus
json.net has a ton of options.Ming
please let me know by which option of JavaScriptSerializer or any other, I could locate the problematic property at run time ?Straus
A
7

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:

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. You can read more in documentation: 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:

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}");
    }
}
Aldric answered 11/4, 2017 at 11:31 Comment(5)
thank you for response, but I wanted to locate specific property which is mapped to not nullable type only. If there is no way to locate then it's a pain to debug manually in huge applications.Straus
not sure you understood my answer, it shows you exactly what you just described...Aldric
I modified my answer a bit to be more understandable and to reflect your changes in the questionAldric
thanks again, I got your answer and your code snippet gives the error causing properties as well, and I've also tried likewise with using reflection too.. but I'm curious to know, is there any Serializer/deserialzer which could locate at run time? without writing any snippet. ?Straus
okay, seems I've to use Json.Net, looks like somewhat close to what I need. Thanks.Straus

© 2022 - 2024 — McMap. All rights reserved.