google/gson · error · NullPointerException
key == null
Error message
key == null
What it means
LinkedTreeMap is a red-black tree keyed by Comparable keys; null is not a valid key (no comparison is possible), so put throws NullPointerException on a null key (LinkedTreeMap.java:108). This mirrors TreeMap's null-key rejection in natural-ordering mode.
Solutions
- Guard the caller: skip, replace, or reject null keys before calling put.
- Use a HashMap/LinkedHashMap if you genuinely need null keys.
- When building maps from untrusted input, normalize keys (e.g. replace null with a sentinel string) at the boundary.
Example fix
// before map.put(maybeNullKey, value); // throws if key null // after if (maybeNullKey != null) map.put(maybeNullKey, value);
Defensive patterns
Strategy: validation
Validate before calling
if (key == null) throw new IllegalArgumentException("key must not be null"); map.put(key, value); Type guard
static <K> boolean puttableKey(LinkedTreeMap<K,?> m, K k) { return k != null; } Try / catch
try { map.put(key, value); } catch (NullPointerException e) { /* handle null key */ } Prevention
- Filter or reject null keys at the boundary that feeds LinkedTreeMap.
- If your data legitimately has null keys, use HashMap/LinkedHashMap instead.
- Annotate map-typed fields with @NotNull when they back a LinkedTreeMap.
When it happens
Trigger: Calling LinkedTreeMap.put(null, value), or any Map.put/computeIfAbsent/merge style call that supplies null as the key, on a LinkedTreeMap instance.
Common situations: Gson's internal JsonObject-like structures backed by LinkedTreeMap when a JSON field name resolves to null (rare for JSON, common with programmatic map construction); generic Map<K,V> code that assumes HashMap-style null keys are tolerated.
Related errors
- value == null
- Element must be non-null
- is not Comparable
- Deserialization is unsupported
- Already wrote a name, expecting a value.
AI-assisted analysis of google/gson@310ac341f2 (2026-08-10).
Data as JSON: /api/errors/c5bed3c5cbd0dcc7.
Report an issue: GitHub.
Appendix: source
Thrown at gson/src/main/java/com/google/gson/internal/LinkedTreeMap.java:109
return size;
}
@Override
public V get(Object key) {
Node<K, V> node = findByObject(key);
return node != null ? node.value : null;
}
@Override
public boolean containsKey(Object key) {
return findByObject(key) != null;
}
@CanIgnoreReturnValue
@Override
public V put(K key, V value) {
if (key == null) {
throw new NullPointerException("key == null");
}
if (value == null && !allowNullValues) {
throw new NullPointerException("value == null");
}
Node<K, V> created = find(key, true);
V result = created.value;
created.value = value;
return result;
}
@Override
public void clear() {
root = null;
size = 0;
modCount++;
// Clear iteration order
Node<K, V> header = this.header;View on GitHub (pinned to 310ac341f2)