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
- Assign via the integer position: myCtor[index] = value.
- Rebuild the JConstructor with the desired arguments rather than keyed assignment.
- 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
- Assign JConstructor arguments by integer position only.
- Rebuild the JConstructor if you need structural change.
- Keep dynamic-keyed mutation out of JConstructor code.
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
- Accessed JConstructor values with invalid key value: {0}. Ar
- Accessed JArray values with invalid key value: {0}. Int32 ar
- Set JArray values with invalid key value: {0}. Int32 array i
- Constructor name cannot be empty.
- An ObjectId must be 12 bytes
AI-assisted analysis of JamesNK/Newtonsoft.Json@4f73e74372 (2026-08-07).
Data as JSON: /api/errors/f2a74d9e392857b2.
Report an issue: GitHub.