JamesNK/Newtonsoft.Json · error · ArgumentException

Can not convert {0} to Int32.

Error message

Can not convert {0} to Int32.

What it means

Thrown by the explicit (non-nullable) cast operator int(JToken) at JToken.cs:815. 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. Non-numeric string contents fail later with FormatException, not this message.

Source

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

            {
                return (char?)integer;
            }
#endif

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

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

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

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

        /// <summary>
        /// Performs an explicit conversion from <see cref="JToken"/> to <see cref="Int16"/>.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <returns>The result of the conversion.</returns>
        public static explicit operator short(JToken value)

View on GitHub (pinned to 4f73e74372)

Solutions

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

Example fix

// before
int count = (int)token["count"]; // throws when count is null

// after
int count = (int?)token["count"] ?? 0;
Defensive patterns

Strategy: type-guard

Validate before calling

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

Try / catch

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

Common situations: An optional count/quantity that returned null; a field re-typed to an object; reading a Date-typed value as an integer index.

Related errors


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