Skip to content

[BUG][JAVA][gson] CustomTypeAdapterFactory throws "Not a JSON Object:null" for null additionalProperties values #24393

Description

@chetan26

Bug Report Checklist

  • Have you provided a full/minimal spec to reproduce the issue?
  • Have you validated the input using an OpenAPI validator?
  • Have you tested with the latest master to confirm the issue still exists?
  • Have you searched for related issues/PRs?
  • What's the actual output vs expected output?
Description

This is a follow-up to #14404/ #17812. The fix handled isJsonArray() in the generated CustomTypeAdapterFactory.write() method (pojo.mustache), but the else branch still calls getAsJsonObject()` unconditionally:

JsonElement jsonElement = gson.toJsonTree(entry.getValue());
if (jsonElement.isJsonArray()) {
  obj.add(entry.getKey(), jsonElement.getAsJsonArray());
} else {
  obj.add(entry.getKey(), jsonElement.getAsJsonObject());
}

If a model has additionalProperties: true and an entry in the undeclared-properties map has a null value (e.g. an unknown field deserialized from a server response that was JSON null), gson.toJsonTree(null) returns JsonNull.INSTANCE. Calling .getAsJsonObject() on a JsonNull throws:

java.lang.IllegalStateException: Not a JSON Object: null at com.google.gson.JsonElement.getAsJsonObject(JsonElement.java:90)

openapi-generator version

master (7.25.0-SNAPSHOT), library=okhttp-gson, generator java

Steps to reproduce

This reproduces with any generated model that has additionalProperties: true, e.g. AdditionalPropertiesClass from the petstore spec:

AdditionalPropertiesClass model = new AdditionalPropertiesClass();
model.putAdditionalProperty("unknownField", null);
model.toJson(); // throws IllegalStateException: Not a JSON Object: null
Related issues/PRs

#14404
#17812

Suggest a fix

Add an isJsonNull() check before the array/object branches in pojo.mustache:

JsonElement jsonElement = gson.toJsonTree(entry.getValue());
if (jsonElement.isJsonNull()) {
  obj.add(entry.getKey(), JsonNull.INSTANCE);
} else if (jsonElement.isJsonArray()) {
  obj.add(entry.getKey(), jsonElement.getAsJsonArray());
} else {
  obj.add(entry.getKey(), jsonElement.getAsJsonObject());
}

plus the corresponding import com.google.gson.JsonNull;

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions