Default nested array to null in java generators (#21713)

* default nested array to null in java generators

* add test schema
This commit is contained in:
William Cheng 2025-08-08 15:59:16 +08:00 committed by GitHub
parent 0f231d9494
commit 89a108aca0
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
9 changed files with 405 additions and 0 deletions

View File

@ -1291,6 +1291,9 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
}
})
.collect(Collectors.joining(", "));
} else if (cp.items.isContainer) {
// TODO nested array/set/map is not supported at the moment so defaulting to null
defaultValue = null;
} else { // array item is non-string, e.g. integer
defaultValue = StringUtils.join(_values, ", ");
}

View File

@ -2809,3 +2809,20 @@ components:
$ref: '#/components/schemas/ArrayOneOf'
anyof_prop:
$ref: '#/components/schemas/ArrayAnyOf'
NestedArrayWithDefaultValues:
type: object
properties:
nestedArray:
type: array
items:
type: array
items:
type: string
default: ["value1", "value2"]
default:
[
[ "h1", "Header 1" ],
[ "h2", "Header 2" ],
[ "h3", "Header 3" ],
[ "h4", "Header 4" ]
]

View File

@ -71,6 +71,7 @@ docs/ModelList.md
docs/ModelReturn.md
docs/ModelWithOneOfAnyOfProperties.md
docs/Name.md
docs/NestedArrayWithDefaultValues.md
docs/NewPet.md
docs/NewPetCategoryInlineAllof.md
docs/NewPetCategoryInlineAllofAllOfCategoryTag.md
@ -216,6 +217,7 @@ src/main/java/org/openapitools/client/model/ModelList.java
src/main/java/org/openapitools/client/model/ModelReturn.java
src/main/java/org/openapitools/client/model/ModelWithOneOfAnyOfProperties.java
src/main/java/org/openapitools/client/model/Name.java
src/main/java/org/openapitools/client/model/NestedArrayWithDefaultValues.java
src/main/java/org/openapitools/client/model/NewPet.java
src/main/java/org/openapitools/client/model/NewPetCategoryInlineAllof.java
src/main/java/org/openapitools/client/model/NewPetCategoryInlineAllofAllOfCategoryTag.java

View File

@ -233,6 +233,7 @@ Class | Method | HTTP request | Description
- [ModelReturn](docs/ModelReturn.md)
- [ModelWithOneOfAnyOfProperties](docs/ModelWithOneOfAnyOfProperties.md)
- [Name](docs/Name.md)
- [NestedArrayWithDefaultValues](docs/NestedArrayWithDefaultValues.md)
- [NewPet](docs/NewPet.md)
- [NewPetCategoryInlineAllof](docs/NewPetCategoryInlineAllof.md)
- [NewPetCategoryInlineAllofAllOfCategoryTag](docs/NewPetCategoryInlineAllofAllOfCategoryTag.md)

View File

@ -2916,6 +2916,27 @@ components:
anyof_prop:
$ref: "#/components/schemas/ArrayAnyOf"
type: object
NestedArrayWithDefaultValues:
properties:
nestedArray:
default:
- - h1
- Header 1
- - h2
- Header 2
- - h3
- Header 3
- - h4
- Header 4
items:
default:
- value1
- value2
items:
type: string
type: array
type: array
type: object
_foo_get_default_response:
example:
string:

View File

@ -0,0 +1,13 @@
# NestedArrayWithDefaultValues
## Properties
| Name | Type | Description | Notes |
|------------ | ------------- | ------------- | -------------|
|**nestedArray** | **List<List<String>>** | | [optional] |

View File

@ -303,6 +303,7 @@ public class JSON {
gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.ModelReturn.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.ModelWithOneOfAnyOfProperties.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.Name.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.NestedArrayWithDefaultValues.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.NewPet.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.NewPetCategoryInlineAllof.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.NewPetCategoryInlineAllofAllOfCategoryTag.CustomTypeAdapterFactory());

View File

@ -0,0 +1,297 @@
/*
* OpenAPI Petstore
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model;
import java.util.Objects;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* NestedArrayWithDefaultValues
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.15.0-SNAPSHOT")
public class NestedArrayWithDefaultValues {
public static final String SERIALIZED_NAME_NESTED_ARRAY = "nestedArray";
@SerializedName(SERIALIZED_NAME_NESTED_ARRAY)
@javax.annotation.Nullable
private List<List<String>> nestedArray;
public NestedArrayWithDefaultValues() {
}
public NestedArrayWithDefaultValues nestedArray(@javax.annotation.Nullable List<List<String>> nestedArray) {
this.nestedArray = nestedArray;
return this;
}
public NestedArrayWithDefaultValues addNestedArrayItem(List<String> nestedArrayItem) {
if (this.nestedArray == null) {
this.nestedArray = new ArrayList<>();
}
this.nestedArray.add(nestedArrayItem);
return this;
}
/**
* Get nestedArray
* @return nestedArray
*/
@javax.annotation.Nullable
public List<List<String>> getNestedArray() {
return nestedArray;
}
public void setNestedArray(@javax.annotation.Nullable List<List<String>> nestedArray) {
this.nestedArray = nestedArray;
}
/**
* A container for additional, undeclared properties.
* This is a holder for any undeclared properties as specified with
* the 'additionalProperties' keyword in the OAS document.
*/
private Map<String, Object> additionalProperties;
/**
* Set the additional (undeclared) property with the specified name and value.
* If the property does not already exist, create it otherwise replace it.
*
* @param key name of the property
* @param value value of the property
* @return the NestedArrayWithDefaultValues instance itself
*/
public NestedArrayWithDefaultValues putAdditionalProperty(String key, Object value) {
if (this.additionalProperties == null) {
this.additionalProperties = new HashMap<String, Object>();
}
this.additionalProperties.put(key, value);
return this;
}
/**
* Return the additional (undeclared) property.
*
* @return a map of objects
*/
public Map<String, Object> getAdditionalProperties() {
return additionalProperties;
}
/**
* Return the additional (undeclared) property with the specified name.
*
* @param key name of the property
* @return an object
*/
public Object getAdditionalProperty(String key) {
if (this.additionalProperties == null) {
return null;
}
return this.additionalProperties.get(key);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
NestedArrayWithDefaultValues nestedArrayWithDefaultValues = (NestedArrayWithDefaultValues) o;
return Objects.equals(this.nestedArray, nestedArrayWithDefaultValues.nestedArray)&&
Objects.equals(this.additionalProperties, nestedArrayWithDefaultValues.additionalProperties);
}
@Override
public int hashCode() {
return Objects.hash(nestedArray, additionalProperties);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class NestedArrayWithDefaultValues {\n");
sb.append(" nestedArray: ").append(toIndentedString(nestedArray)).append("\n");
sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>(Arrays.asList("nestedArray"));
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>(0);
}
/**
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to NestedArrayWithDefaultValues
*/
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!NestedArrayWithDefaultValues.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in NestedArrayWithDefaultValues is not found in the empty JSON string", NestedArrayWithDefaultValues.openapiRequiredFields.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
// ensure the optional json data is an array if present
if (jsonObj.get("nestedArray") != null && !jsonObj.get("nestedArray").isJsonNull() && !jsonObj.get("nestedArray").isJsonArray()) {
throw new IllegalArgumentException(String.format("Expected the field `nestedArray` to be an array in the JSON string but got `%s`", jsonObj.get("nestedArray").toString()));
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!NestedArrayWithDefaultValues.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'NestedArrayWithDefaultValues' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<NestedArrayWithDefaultValues> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(NestedArrayWithDefaultValues.class));
return (TypeAdapter<T>) new TypeAdapter<NestedArrayWithDefaultValues>() {
@Override
public void write(JsonWriter out, NestedArrayWithDefaultValues value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
obj.remove("additionalProperties");
// serialize additional properties
if (value.getAdditionalProperties() != null) {
for (Map.Entry<String, Object> entry : value.getAdditionalProperties().entrySet()) {
if (entry.getValue() instanceof String)
obj.addProperty(entry.getKey(), (String) entry.getValue());
else if (entry.getValue() instanceof Number)
obj.addProperty(entry.getKey(), (Number) entry.getValue());
else if (entry.getValue() instanceof Boolean)
obj.addProperty(entry.getKey(), (Boolean) entry.getValue());
else if (entry.getValue() instanceof Character)
obj.addProperty(entry.getKey(), (Character) entry.getValue());
else {
JsonElement jsonElement = gson.toJsonTree(entry.getValue());
if (jsonElement.isJsonArray()) {
obj.add(entry.getKey(), jsonElement.getAsJsonArray());
} else {
obj.add(entry.getKey(), jsonElement.getAsJsonObject());
}
}
}
}
elementAdapter.write(out, obj);
}
@Override
public NestedArrayWithDefaultValues read(JsonReader in) throws IOException {
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
NestedArrayWithDefaultValues instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {
if (!openapiFields.contains(entry.getKey())) {
if (entry.getValue().isJsonPrimitive()) { // primitive type
if (entry.getValue().getAsJsonPrimitive().isString())
instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString());
else if (entry.getValue().getAsJsonPrimitive().isNumber())
instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber());
else if (entry.getValue().getAsJsonPrimitive().isBoolean())
instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean());
else
throw new IllegalArgumentException(String.format("The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString()));
} else if (entry.getValue().isJsonArray()) {
instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class));
} else { // JSON object
instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class));
}
}
}
return instance;
}
}.nullSafe();
}
}
/**
* Create an instance of NestedArrayWithDefaultValues given an JSON string
*
* @param jsonString JSON string
* @return An instance of NestedArrayWithDefaultValues
* @throws IOException if the JSON string is invalid with respect to NestedArrayWithDefaultValues
*/
public static NestedArrayWithDefaultValues fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, NestedArrayWithDefaultValues.class);
}
/**
* Convert an instance of NestedArrayWithDefaultValues to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@ -0,0 +1,50 @@
/*
* OpenAPI Petstore
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
/**
* Model tests for NestedArrayWithDefaultValues
*/
public class NestedArrayWithDefaultValuesTest {
private final NestedArrayWithDefaultValues model = new NestedArrayWithDefaultValues();
/**
* Model tests for NestedArrayWithDefaultValues
*/
@Test
public void testNestedArrayWithDefaultValues() {
// TODO: test NestedArrayWithDefaultValues
}
/**
* Test the property 'nestedArray'
*/
@Test
public void nestedArrayTest() {
// TODO: test nestedArray
}
}