Bug Report Checklist
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;
Bug Report Checklist
Description
This is a follow-up to #14404/ #17812. The fix handled
isJsonArray()in the generatedCustomTypeAdapterFactory.write()method (pojo.mustache), but theelse branch still callsgetAsJsonObject()` unconditionally:If a model has
additionalProperties: trueand an entry in the undeclared-properties map has anullvalue (e.g. an unknown field deserialized from a server response that was JSON null), gson.toJsonTree(null) returnsJsonNull.INSTANCE. Calling.getAsJsonObject()on aJsonNullthrows: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.AdditionalPropertiesClassfrom the petstore spec:Related issues/PRs
#14404
#17812
Suggest a fix
Add an is
JsonNull()check before the array/object branches inpojo.mustache:plus the corresponding import
com.google.gson.JsonNull;