Newtonsoft.Json.JsonSerializationException: ‘Error converting value {null} to type “System.Boolean”.

Code like this can generate the error:

someList.Add(JsonConvert.DeserializeObject<DestinationModel>(JsonConvert.SerializeObject(sourceModelItem)));

This happens when the bool field in your source is null, and the model you’re converting into’s matching field does not allow nulls.

If you don’t mind this field being null in your destination model item, then you can just make that field nullable by adding a ? to the type:

public bool? MyBoolField { get; set; }

However, if you have code that expects this field to contain bools then you’ll run into problems later! Stack overflow has a lot of discussions on alternatives.

Last modified: June 29, 2021

Author

Comments

Write a Reply or Comment

Your email address will not be published.