-1

I'm trying to Serialize a Response object to Json format and then to Desirialize it back to Response object. But when I'm trying to access a ReturnValue field inside the desirialized Response object I get this ValueKind type and I can't find a way to access its value.

  • I'm using only System.Text.Json
  • I'm Serialising like this:
    string jsonRes = JsonSerializer.Serialize(new Response(null,5));
  • Trying to Desirialise like this:
    Response res = JsonSerializer.Deserialize<Response>(jsonRes);
  • Then I'm trying to compare the ReturnValue field inside the Response object like this:
    res.ReturnValue.Equals(5)

An image of what I get when trying to access the ReturnValue inside the Response class

  • The Response class:
public class Response
    {
        public string ErrorMessage { get; set; }
        public object ReturnValue { get; set; }


        public Response()
        {
        }
      
        public Response(string message, object obj = null)
        {
            this.ErrorMessage = message;
            this.ReturnValue = obj;
        }
   }
  • See [Is polymorphic deserialization possible in System.Text.Json?](https://stackoverflow.com/q/58074304/3744182). Answer is *yes, but you must write a custom converter.* – dbc Jun 03 '22 at 21:52
  • `if (((int)res.ReturnValue).Equals(5))`- if you know it's an integer (which it must be to campare to `5`). – Poul Bak Jun 04 '22 at 11:13
  • `ìf (res.ReturnValue is int res && res.equals(5))` is another option. – Poul Bak Jun 04 '22 at 11:16

2 Answers2

0

One way to work around that is to make your Response class generic so you can provide an expected type for serializer:

public class Response<T>
{
    public string ErrorMessage { get; set; }
    public T ReturnValue { get; set; }


    public Response()
    {
    }
  
    public Response(string message, T obj = default)
    {
        this.ErrorMessage = message;
        this.ReturnValue = obj;
    }
}

And usage:

string jsonRes = JsonSerializer.Serialize(new Response<int>(null,5));
var res = JsonSerializer.Deserialize<Response<int>>(jsonRes);
Assert.AreEqual(5, res.ReturnValue);
Guru Stron
  • 42,843
  • 5
  • 48
  • 70
-1

I have fixed the problem by Deserializing the response.ReturnValue field like this:

JsonSerializer.Deserialize<int>((JsonElement)response.ReturnValue);
Tyler2P
  • 2,182
  • 12
  • 17
  • 28