JamesNK/Newtonsoft.Json · error · ArgumentException

Set JConstructor values with invalid key value: {0}. Argumen

Error message

Set JConstructor values with invalid key value: {0}. Argument position index expected.

What it means

Thrown by the JConstructor[object key] setter when assigning with a non-int key. Like the getter, JConstructor arguments are positional.

Source

Thrown at Src/Newtonsoft.Json/Linq/JConstructor.cs:205

        {
            get
            {
                ValidationUtils.ArgumentNotNull(key, nameof(key));

                if (!(key is int i))
                {
                    throw new ArgumentException("Accessed JConstructor values with invalid key value: {0}. Argument position index expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key)));
                }

                return GetItem(i);
            }
            set
            {
                ValidationUtils.ArgumentNotNull(key, nameof(key));

                if (!(key is int i))
                {
                    throw new ArgumentException("Set JConstructor values with invalid key value: {0}. Argument position index expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key)));
                }

                SetItem(i, value);
            }
        }

        internal override int GetDeepHashCode()
        {
            int hash;
#if HAVE_GETHASHCODE_STRING_COMPARISON
            hash = _name?.GetHashCode(StringComparison.Ordinal) ?? 0;
#else
            hash = _name?.GetHashCode() ?? 0;
#endif
            return hash ^ ContentsHashCode();
        }

        /// <summary>

View on GitHub (pinned to 4f73e74372)

Solutions

  1. Assign via the integer position: myCtor[index] = value.
  2. Rebuild the JConstructor with the desired arguments rather than keyed assignment.
  3. Guard the key type before assignment.

Example fix

// before
myCtor[(object)key] = new JValue(1);
// after
myCtor[0] = new JValue(1);
Defensive patterns

Strategy: type-guard

Validate before calling

if (key is int i) { ctor[i] = value; }
else throw new InvalidOperationException("JConstructor setter requires an int argument index.");

Type guard

static bool IsCtorKey(object key) => key is int;

Try / catch

try { ctor[key] = value; }
catch (ArgumentException ex) when (ex.Message.Contains("Argument position index expected")) {
    // coerce key to int
}

Prevention

When it happens

Trigger: Assigning myCtor["x"] = token or using a non-int boxed key on the set side.

Common situations: Mutating constructor arguments with code patterned after JObject; dynamic key types.

Related errors


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