JamesNK/Newtonsoft.Json · error · ArgumentNullException

key

Error message

key

What it means

JPropertyKeyedCollection.Contains(string key) throws ArgumentNullException 'key' (JPropertyKeyedCollection.cs:84) when the supplied property name is null. JObject lookups are keyed by non-null strings, so passing null — usually an uninitialized or missing variable — is rejected at the boundary.

Source

Thrown at Src/Newtonsoft.Json/Linq/JPropertyKeyedCollection.cs:84

                if (keyForItem != null)
                {
                    RemoveKey(keyForItem);
                }
            }
        }

        protected override void ClearItems()
        {
            base.ClearItems();

            _dictionary?.Clear();
        }

        public bool Contains(string key)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            if (_dictionary != null)
            {
                return _dictionary.ContainsKey(key);
            }

            return false;
        }

        private bool ContainsItem(JToken item)
        {
            if (_dictionary == null)
            {
                return false;
            }

            string key = GetKeyForItem(item);

View on GitHub (pinned to 4f73e74372)

Solutions

  1. Null-check the key variable before calling Contains/Property.
  2. Trace where the null originated (config, dictionary lookup, optional field) and provide a default.
  3. Use string.IsNullOrWhiteSpace guards at API boundaries.

Example fix

// before
string name = GetNameFromConfig(); // may be null
bool has = obj.ContainsKey(name); // throws ArgumentNullException

// after
string name = GetNameFromConfig();
bool has = name != null && obj.ContainsKey(name);
Defensive patterns

Strategy: validation

Validate before calling

string name = GetKeyFromConfig();
bool has = !string.IsNullOrEmpty(name) && obj.ContainsKey(name);

Type guard

static bool IsValidKey(string? key) => !string.IsNullOrEmpty(key);

Prevention

When it happens

Trigger: Calling a JObject membership check (e.g. obj.ContainsKey(name), obj.Property(name)) with a null name argument — commonly a variable that came back null from config, a dictionary miss, or a missing JSON field used as a key.

Common situations: Using a downstream/derived string as a property key without null-checking it; reading a key name from configuration or another JSON field that was absent.

Related errors


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