Home > Mobile >  Read in Byte value and convert to Null
Read in Byte value and convert to Null

Time:05-03

I am trying to write a function that handles empty values for the datatype Byte.

The reader is reading in a JSON string and serializing to my models.

One of the models has a Byte property.

If the reader encounters a blank or empty string for a Byte, then it should convert it to Null.

But whenever the function is used, I get this error:

System.InvalidOperationException: 'Cannot get the value of a token type 'String' as a number.'

Here is my function:

    public override Byte? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        var @byte = reader.GetByte();
        if (string.IsNullOrWhiteSpace(@byte.ToString()))
        {
            return null;
        }
        return Byte.Parse(@byte.ToString());
    }

I am not sure why it is giving me the error or how to fix?

Thanks!

CodePudding user response:

It seems that your issue is that you have a string value in from JSON and you're trying to read that as a Byte. Instead, you should try reading it as a string first:

public override Byte? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
    string raw = reader.GetString();
    if (string.IsNullOrWhiteSpace(raw)) {
        return null;
    }

    return Byte.Parse(raw);
}

This will do what you want: parse the data as a Byte if it's available or return null if it's empty or missing. As an aside, you should really make use of type-checking to ensure a broader use-case rather than relying on a string-input.

CodePudding user response:

While I don't think is an elegant solution or even a proper one, I got this to work by 1) Checking the TokenType and 2) converting it to an int to check for null or empty.

    public override Byte? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        var tokenType = reader.TokenType;
        if(tokenType == JsonTokenType.Number)
        {
            var @byte = reader.GetByte();
            var intVal = Convert.ToInt32(@byte);
            if (string.IsNullOrWhiteSpace(intVal.ToString()))
            {
                return null;
            }
            return @byte;
        }
        return null;
    }
  • Related