'Read in Byte value and convert to Null
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!
Solution 1:[1]
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.
Solution 2:[2]
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;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Woody1193 |
| Solution 2 | SkyeBoniwell |
