Home > Mobile >  How to get rid of ValueKind when using System.Text.Json Desirialise
How to get rid of ValueKind when using System.Text.Json Desirialise

Time:06-04

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;
        }
   }

CodePudding user response:

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);

CodePudding user response:

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

JsonSerializer.Deserialize<int>((JsonElement)response.ReturnValue);
  • Related