Skip to content

[Java][Spring] default value of Arrays and Maps is empty collection #5685

@stevecookform3

Description

@stevecookform3
Description

Currently codegen generates empty collections for arrays and maps e.g.

  @SerializedName("data")
  private List<Account> data = new ArrayList<Account>();

The problem is that by the time the model is deserialised from json, there is no way for the API to distinguish between a missing value and an empty array. This is particularly a problem when building REST PATCH handlers, where we'd like to distinguish between field = null (meaning dont change it - use the current value) and field = [] (meaning, set it to an empty array).

Ideally we'd either just set the empty collection to null e.g.

  @SerializedName("data")
  private List<Account> data = null;

If this is considered a breaking change, we could introduce an optional switch in codegen to determine which behaviour is required (null vs. empty collection for uninitialised fields).

Swagger-codegen version

latest head

Command line used for generation

generate -i swagger.yaml -l spring

Steps to reproduce

Add an array or map to a model, and look at the source code.

Related issues
Suggest a Fix

Relevant code is in: https://github.com/swagger-api/swagger-codegen/blob/master/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java

    @Override
    public String toDefaultValue(Property p) {
        if (p instanceof ArrayProperty) {
            final ArrayProperty ap = (ArrayProperty) p;
            final String pattern;
            if (fullJavaUtil) {
                pattern = "new java.util.ArrayList<%s>()";
            } else {
                pattern = "new ArrayList<%s>()";
            }
            if (ap.getItems() == null) {
                return null;
            }
            return String.format(pattern, getTypeDeclaration(ap.getItems()));
        } else if (p instanceof MapProperty) {
            final MapProperty ap = (MapProperty) p;
            final String pattern;
            if (fullJavaUtil) {
                pattern = "new java.util.HashMap<String, %s>()";
            } else {
                pattern = "new HashMap<String, %s>()";
            }
            if (ap.getAdditionalProperties() == null) {
                return null;
            }
            return String.format(pattern, getTypeDeclaration(ap.getAdditionalProperties()));
        }

change to:

    @Override
    public String toDefaultValue(Property p) {
        if (p instanceof ArrayProperty) {
            return "null";
        } else if (p instanceof MapProperty) {
            return "null";
        }

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions