Background
I need to override the below method so it will deserialize an object's property without failing.
JsonConvert.DeserializeObject()
It is failing because it is trying to convert a key pair value which contains either "Y" or "N" to a property which is of type Boolean.
This is the error
Could not convert string to boolean: Y.
I'm calling the method like this:
private List<T> GetBindingSource<T>(List<T> list, string JsonKey, Dictionary<string, string> dictOriginalJSON)
{
var OutJson = "";
if (dictOriginalJSON.TryGetValue(JsonKey, out OutJson))
{
list = JsonConvert.DeserializeObject<List<T>>(OutJson); //Call fails here
}
return list;
}
My Attempted Solution
After reading up on the issue it seems the best thing to do would be to override the method. I've chosen this solution by #entre
How to get newtonsoft to deserialize yes and no to boolean
using System;
using Newtonsoft.Json;
namespace JsonConverters
{
public class BooleanJsonConverter : JsonConverter
{
public override bool CanConvert( Type objectType )
{
return objectType == typeof( bool );
}
public override object ReadJson( JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer )
{
switch ( reader.Value.ToString().ToLower().Trim() )
{
case "true":
case "yes":
case "y":
case "1":
return true;
case "false":
case "no":
case "n":
case "0":
return false;
}
// If we reach here, we're pretty much going to throw an error so let's let Json.NET throw it's pretty-fied error message.
return new JsonSerializer().Deserialize( reader, objectType );
}
public override void WriteJson( JsonWriter writer, object value, JsonSerializer serializer )
{
}
Problem
When I make the new call to the extended class like below.
list = BooleanJsonConverter.DeserializeObject<List<T>>(OutJson);
I get this error message.
QueueDetail.BooleanJsonConverter' does not contain a definition for 'DeserializeObject'
Question
What am I doing wrong? This is the first time I've attempted this, so I may well be missing something.
If BooleanJsonConverter
inherits JsonConverter
. Why doesn't BooleanJsonConverter contain the call i was using previously ?