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

  1. Assign via the int indexer: myArray[index] = value.
  2. To append, call myArray.Add(value); to overwrite an existing slot use the integer position.
  3. 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

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


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