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

anoop picture anoop · Apr 11, 2017 · Viewed 7.4k times · Source

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?

Answer

Pawel Gradecki picture Pawel Gradecki · Apr 11, 2017

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