google/gson · error · NullPointerException

value == null

Error message

value == null

What it means

LinkedTreeMap can be constructed in a mode that disallows null values (allowNullValues=false). put throws NullPointerException when a null value is supplied and the map does not permit null values (LinkedTreeMap.java:111). This is stricter than HashMap to surface accidental null writes.

Solutions

  1. Construct the map allowing null values if your data needs them: new LinkedTreeMap<>(true) or new LinkedTreeMap<>(comparator, true).
  2. Skip or substitute the entry when the value is null instead of storing it.
  3. Use a different Map implementation (HashMap/LinkedHashMap) if null values are intrinsic to your design.

Example fix

// before
LinkedTreeMap<String,String> m = new LinkedTreeMap<>(); // allowNullValues defaults true but you may pass false
m.put("k", null);
// after
LinkedTreeMap<String,String> m = new LinkedTreeMap<>(true); // explicitly allow null values
Defensive patterns

Strategy: validation

Validate before calling

if (value == null) throw new IllegalArgumentException("value null not allowed"); map.put(key, value);

Type guard

static <V> boolean puttableValue(LinkedTreeMap<?,V> m, V v) { return v != null || m.allowsNullValues(); }

Try / catch

try { map.put(k, v); } catch (NullPointerException e) { /* value null + not allowed */ }

Prevention

When it happens

Trigger: Calling put(k, null) on a LinkedTreeMap created with new LinkedTreeMap(false) or new LinkedTreeMap(comparator, false).

Common situations: Code assuming HashMap-like null values; deserializing JSON with missing fields into a model that maps to a null-valued LinkedTreeMap; switching from a permissive map to LinkedTreeMap without enabling null values.

Related errors


AI-assisted analysis of google/gson@310ac341f2 (2026-08-10). Data as JSON: /api/errors/1ab636af12cb74e4. Report an issue: GitHub.

Appendix: source

Thrown at gson/src/main/java/com/google/gson/internal/LinkedTreeMap.java:112

  @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;
    header.next = header.prev = header;
  }

View on GitHub (pinned to 310ac341f2)