JamesNK/Newtonsoft.Json · error · ArgumentException
Set JArray values with invalid key value: {0}. Int32 array i
Error message
Set JArray values with invalid key value: {0}. Int32 array index expected. What it means
Thrown by the JArray[object key] setter when assigning through the object-key indexer with a key that is neither int nor System.Index. The set path mirrors the get path and requires an integer position.
Source
Thrown at Src/Newtonsoft.Json/Linq/JArray.cs:279
}
}
set
{
ValidationUtils.ArgumentNotNull(key, nameof(key));
switch (key)
{
case int intKey:
SetItem(intKey, value);
return;
#if NET6_0_OR_GREATER
case Index indexKey:
SetItem(indexKey.GetOffset(Count), value);
return;
#endif
default:
throw new ArgumentException("Set JArray values with invalid key value: {0}. Int32 array index expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key)));
}
}
}
/// <summary>
/// Gets or sets the <see cref="Newtonsoft.Json.Linq.JToken"/> at the specified index.
/// </summary>
/// <value></value>
public JToken this[int index]
{
get => GetItem(index);
set => SetItem(index, value);
}
internal override int IndexOfItem(JToken? item)
{
if (item == null)
{View on GitHub (pinned to 4f73e74372)
Solutions
- Assign via the int indexer: myArray[index] = value.
- To append, call myArray.Add(value); to overwrite an existing slot use the integer position.
- Validate the key type before assignment when the index comes from dynamic input.
Example fix
// before myArray[(object)keyStr] = new JValue(1); // after myArray[0] = new JValue(1);
Defensive patterns
Strategy: type-guard
Validate before calling
if (key is int i) { arr[i] = value; }
else throw new InvalidOperationException("JArray setter requires an int index."); Type guard
static bool IsArrayKey(object key) => key is int
#if NET6_0_OR_GREATER
|| key is System.Index
#endif
; Try / catch
try { arr[key] = value; }
catch (ArgumentException ex) when (ex.Message.Contains("Int32 array index expected")) {
// convert key to int or use Add
} Prevention
- Assign via arr[int] = value.
- Use Add to append rather than assigning past the end.
- Keep JArray mutation code typed to int indices.
When it happens
Trigger: Assigning myArray["name"] = token, or using a boxed long/double as the index on the setter side.
Common situations: Building or mutating a JArray with code ported from JObject; dynamic dispatch passing a non-int key.
Related errors
- Accessed JArray values with invalid key value: {0}. Int32 ar
- Object serialized to {0}. JArray instance expected.
- Accessed JConstructor values with invalid key value: {0}. Ar
- Set JConstructor values with invalid key value: {0}. Argumen
- An ObjectId must be 12 bytes
AI-assisted analysis of JamesNK/Newtonsoft.Json@4f73e74372 (2026-08-07).
Data as JSON: /api/errors/8404e6cc6601fe10.
Report an issue: GitHub.