Search code examples
c#asp.netjsonjson.netdeserialization

Error in deserializing generic boolean to object in NewtonSoft Json?


I know this type of question has been asked many times before but I really cannot figure it out. I send this object from a controller:

OperationResult<bool>()
{
   IsSuccess = true,
   Result = default,
   Error = null
};

I receive this json string in front-end:

'{"result":false,"error":null,"isSuccess":true}'

And I try to deserialize it like this:

var result = JsonConvert.DeserializeObject<OperationResult<R>>(jsonstring);

This is the type of object I'm trying to deserialize the json to:

    public class OperationResult<R>
    {
        public OperationResult()
        {
        }

        public R Result { get; set; }
        public string Error { get; set; }
        public bool IsSuccess { get; set; } 
    }

At deserialization I get this exception:

Error converting value False to type OperationResult`1[System.Boolean]

This is the inner exception:

Could not cast or convert from System.Boolean to OperationResult`1[System.Boolean].

The weird thing is that I receive this error only when R is of type boolean.

To be honest I have not tried anything except to change types from boolean to another type to see if the serialization works. I don't know what else to do.


Solution

  • I tested your code in VS, everything works properly, no problem

    static void Main()
    {
        var json="{\"result\":false,\"error\":null,\"isSuccess\":true}";
        var result = JsonConvert.DeserializeObject<OperationResult<bool>>(json);
        json = JsonConvert.SerializeObject(result, Newtonsoft.Json.Formatting.Indented);
    }
    

    result

    {
      "Result": false,
      "Error": null,
      "IsSuccess": true
    }
    

    class

    public class OperationResult<T>
    {
        public T Result { get; set; }
        public string Error { get; set; }
        public bool IsSuccess { get; set; }
    }