Resolving: Newtonsoft.Json.JsonReaderException: Could not convert string to boolean

Issue Description

Newtonsoft.Json serialization gives error while converting the string to boolean types.

Newtonsoft.Json.JsonReaderException: ‘Could not convert string to boolean: 1. Path ‘[0].ID’, line 1, position 10.’

NewtonsoftJsonJsonReaderException'Could not convert string to boolean

Resolution

This issue can be resolved by using a few approaches. The simplest approach would be to use a custom JSON converter so as to be able to serialize the required properties as required in the target object.

In the above case, i can create a Custom boolean converter to generate the required serialization objects.

Sample converter used as below,

        var result = JsonConvert.SerializeObject(excelasTable);
                var generatedType = JsonConvert.DeserializeObject<T>(result, new CustomBooleanJsonConverter());
                return (T)Convert.ChangeType(generatedType, typeof(T));

Custom Boolean JSON Converter

Custom Boolean Json Converter created as below which can be passed as the second argument to DeserializeObject method.

JsonConvert.DeserializeObject<T>(result, new CustomBooleanJsonConverter());

Please remember to override two below method,

  • ReadJson
  • WriteJson

public class CustomBooleanJsonConverter : JsonConverter<bool>
        {
            public override bool ReadJson(JsonReader reader, Type objectType, bool existingValue, bool hasExistingValue, JsonSerializer serializer)
            {
                return Convert.ToBoolean(reader.ValueType == typeof(string) ? Convert.ToByte(reader.Value) : reader.Value);
            }

            public override void WriteJson(JsonWriter writer, bool value, JsonSerializer serializer)
            {
                serializer.Serialize(writer, value);
            }
        }

That’s all. The issue is resolved!

Did I miss anything else in these resolution steps?

Did the above steps resolve your issue? Please sound off your comments below!

Happy Coding !!



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



Leave a Reply

Your email address will not be published. Required fields are marked *