JamesNK/Newtonsoft.Json · error · ArgumentException

Can not convert {0} to Int64.

Error message

Can not convert {0} to Int64.

What it means

Thrown by the explicit (non-nullable) cast operator long(JToken) at JToken.cs:643. The token type must be in NumberTypes = {Integer, Float, String, Comment, Raw, Boolean}. A JSON null, a Date/Guid/Uri/TimeSpan/Bytes value, or a container (JObject/JArray) fails this ArgumentException. Note String IS allowed (the digits are parsed by Convert.ToInt64), so only non-numeric strings fail later with a FormatException, not this message.

Source

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

            {
                return Convert.ToBoolean((int)integer);
            }
#endif

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

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

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

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

        /// <summary>
        /// Performs an explicit conversion from <see cref="JToken"/> to <see cref="Nullable{T}"/> of <see cref="DateTime"/>.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <returns>The result of the conversion.</returns>
        public static explicit operator DateTime?(JToken? value)

View on GitHub (pinned to 4f73e74372)

Solutions

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

Example fix

// before
long id = (long)token["id"]; // throws when id is null

// after
long id = (long?)token["id"] ?? 0;
Defensive patterns

Strategy: type-guard

Validate before calling

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

Try / catch

try
{
    long l = (long)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 (long)token; casting a JTokenType.Date/Boolean(Guid-style)/Object/Array to long; a token whose Type is Null because the field was omitted.

Common situations: An optional numeric ID that came back as JSON null; a field represented as an object or array instead of an integer; reading a Date-typed value as a number.

Related errors


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