JamesNK/Newtonsoft.Json · error · ArgumentException

Can not convert {0} to UInt32.

Error message

Can not convert {0} to UInt32.

What it means

Thrown by the explicit cast operator 'operator uint?(JToken?)' (Nullable<UInt32>) when the token is not resolvable to a numeric JValue. ArgumentException {0} is the resolved JTokenType; allowed types are NumberTypes ({Integer, Float, String, Comment, Raw, Boolean}). Nullable overload, so null/JSON-null return null; the throw means a structurally non-numeric shape.

Source

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

        }

        /// <summary>
        /// Performs an explicit conversion from <see cref="JToken"/> to <see cref="Nullable{T}"/> of <see cref="UInt32"/>.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <returns>The result of the conversion.</returns>
        [CLSCompliant(false)]
        public static explicit operator uint?(JToken? value)
        {
            if (value == null)
            {
                return null;
            }

            JValue? v = EnsureValue(value);
            if (v == null || !ValidateToken(v, NumberTypes, true))
            {
                throw new ArgumentException("Can not convert {0} to UInt32.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
            }

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

            return (v.Value != null) ? (uint?)Convert.ToUInt32(v.Value, CultureInfo.InvariantCulture) : null;
        }

        /// <summary>
        /// Performs an explicit conversion from <see cref="JToken"/> to <see cref="Nullable{T}"/> of <see cref="UInt64"/>.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <returns>The result of the conversion.</returns>
        [CLSCompliant(false)]

View on GitHub (pinned to 4f73e74372)

Solutions

  1. Guard token["count"]?.Type is in {Integer, Float, String, Boolean} before casting.
  2. Use token["count"]?.Value<uint>() to get a non-throwing default on mismatch.
  3. Confirm values are non-negative before choosing the unsigned overload (else use int?/long?).
  4. Re-check your indexing to ensure you reached the scalar counter node.

Example fix

// before
uint? count = (uint?)payload["count"]; // throws when count is an object

// after
uint? count = payload["count"]?.Type == JTokenType.Integer ? payload["count"]!.Value<uint>() : null;
Defensive patterns

Strategy: validation

Validate before calling

uint? count = payload["count"]?.Type == JTokenType.Integer ? payload["count"]!.Value<uint>() : null;

Type guard

static bool IsUnsignedNumeric(JToken? t) =>
    t is JValue v && (v.Type == JTokenType.Integer || v.Type == JTokenType.Float);

Try / catch

uint? count;
try { count = (uint?)payload["count"]; }
catch (ArgumentException) { count = null; }

Prevention

When it happens

Trigger: Calling (uint?)token["count"] where the resolved JTokenType is Date, Guid, TimeSpan, Uri, Bytes, Object, or Array, or the node is a JObject/JArray (EnsureValue null). A negative integer string does NOT throw this — it passes ValidateToken and throws OverflowException from Convert.ToUInt32.

Common situations: Unsigned counter field occasionally replaced by a date or object; schema change from integer to GUID string; mis-indexed node returning a child array.

Related errors


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