JamesNK/Newtonsoft.Json · error · ArgumentException

Can not convert {0} to Byte.

Error message

Can not convert {0} to Byte.

What it means

Thrown by the explicit (non-nullable) cast operator byte(JToken) at JToken.cs:909. The token type must be in NumberTypes = {Integer, Float, String, Comment, Raw, Boolean}. A JSON null, a Date/Guid/Uri/Bytes value, or a container (JObject/JArray) fails this ArgumentException. Out-of-range/negative values fail later with OverflowException.

Source

Thrown at Src/Newtonsoft.Json/Linq/JToken.cs:909

            {
                return (char)integer;
            }
#endif

            return Convert.ToChar(v.Value, CultureInfo.InvariantCulture);
        }

        /// <summary>
        /// Performs an explicit conversion from <see cref="JToken"/> to <see cref="Byte"/>.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <returns>The result of the conversion.</returns>
        public static explicit operator byte(JToken value)
        {
            JValue? v = EnsureValue(value);
            if (v == null || !ValidateToken(v, NumberTypes, false))
            {
                throw new ArgumentException("Can not convert {0} to Byte.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
            }

#if HAVE_BIG_INTEGER
            if (v.Value is BigInteger integer)
            {
                return (byte)integer;
            }
#endif

            return Convert.ToByte(v.Value, CultureInfo.InvariantCulture);
        }

        /// <summary>
        /// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="System.SByte"/>.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <returns>The result of the conversion.</returns>
        [CLSCompliant(false)]

View on GitHub (pinned to 4f73e74372)

Solutions

  1. Use the nullable cast (byte?)token and coalesce: ((byte?)token) ?? (byte)0.
  2. Guard with token.Type == JTokenType.Integer before the cast.
  3. Use token.Value<byte?>() to tolerate null/missing.
  4. Deserialize into a nullable byte POCO property.

Example fix

// before
byte channel = (byte)token["channel"]; // throws when channel is null

// after
byte channel = (byte?)token["channel"] ?? (byte)0;
Defensive patterns

Strategy: type-guard

Validate before calling

// Verify the token is a number-compatible scalar before the non-nullable byte cast
static bool CanToByte(JToken? t) =>
    t is JValue v && (v.Type == JTokenType.Integer || v.Type == JTokenType.Float
                      || v.Type == JTokenType.String || v.Type == JTokenType.Boolean);

Type guard

static byte? SafeByte(JToken? t) => t switch {
    JValue v when v.Type is JTokenType.Integer or JTokenType.Float
                       or JTokenType.String or JTokenType.Boolean => (byte?)t,
    JValue v when v.Type is JTokenType.Null or JTokenType.Undefined => null,
    _ => null
};

Try / catch

try
{
    byte b = (byte)token;
}
catch (ArgumentException ex) when (ex.Message.StartsWith("Can not convert"))
{
    // token is null/container/date; default to 0
}

Prevention

When it happens

Trigger: Casting a JSON null JValue to (byte)token; casting a Date/Object/Array/Guid to byte; an omitted byte field parsed as null.

Common situations: A byte field (e.g. a small flag or channel) that came back null or as an object; reading a Date value as a byte.

Related errors


AI-assisted analysis of JamesNK/Newtonsoft.Json@4f73e74372 (2026-08-07). Data as JSON: /api/errors/61e938d7ab38d12a. Report an issue: GitHub.