JamesNK/Newtonsoft.Json · error · ArgumentException

Can not convert {0} to UInt16.

Error message

Can not convert {0} to UInt16.

What it means

Thrown by the explicit (non-nullable) cast operator ushort(JToken) at JToken.cs:862. 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. Negative numbers would fail later with OverflowException.

Source

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

                return (short)integer;
            }
#endif

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

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

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

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

        /// <summary>
        /// Performs an explicit conversion from <see cref="JToken"/> to <see cref="Char"/>.
        /// </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 (ushort?)token and coalesce: ((ushort?)token) ?? (ushort)0.
  2. Guard with token.Type == JTokenType.Integer before the cast.
  3. Use token.Value<ushort?>() to tolerate null/missing.
  4. Deserialize into a nullable ushort POCO property.

Example fix

// before
ushort port = (ushort)token["port"]; // throws when port is null

// after
ushort port = (ushort?)token["port"] ?? (ushort)0;
Defensive patterns

Strategy: type-guard

Validate before calling

// Verify the token is a number-compatible scalar before the non-nullable ushort cast
static bool CanToUShort(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 ushort? SafeUShort(JToken? t) => t switch {
    JValue v when v.Type is JTokenType.Integer or JTokenType.Float
                       or JTokenType.String or JTokenType.Boolean => (ushort?)t,
    JValue v when v.Type is JTokenType.Null or JTokenType.Undefined => null,
    _ => null
};

Try / catch

try
{
    ushort u = (ushort)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 (ushort)token; casting a Date/Object/Array/Guid to ushort; an omitted unsigned field parsed as null.

Common situations: A port number or unsigned identifier that came back null or as an object; reading a Date value as a ushort.

Related errors


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