swagger-api / swagger-api/swagger-codegen

[JAVA][SPRING] Swagger codegen generates wrong java object for json objects with additional properties

Open
#5,187 10 comments 8 reactions 1 assignee View on GitHub

@HugoMario is already working on this.

Since Aug 14, 2020.

Client: Java Issue: Bug Server: Spring
Dominant language
Mustache
Stars
17.8k
Forks
6k
PR merge metrics
No merged PRs in 30d

Description

Description

Swagger Codegen generates a java model object that extends HashMap for json objects that have the additionalProperties: property set. This leads to jackson only serealizing the properties added to the hashmap and ignoring all additional properties that are set explicitly in the java file.

Swagger-codegen version

2.2.2

Swagger declaration file content or url
 Datavalue:
    type: object
    description: The individual dataelements 
    required:
      - id
    properties:
      id:
        type: string
      source:
        type: string
      target:
        type: string
    additionalProperties:
      type: string

This generates a model object that starts like this:

public class Datavalue extends HashMap<String, String>  {
  @JsonProperty("id")
  private String id = null;

  @JsonProperty("source")
  private String source = null;

  @JsonProperty("target")
  private String target = null;

  public Datavalue id(String id) {
    this.id = id;
    return this;
  }

Serializing this objects leads to a json that is missing the explicitly set properties (id, source, target).
http://stackoverflow.com/questions/31320983/jackson-serialise-map-with-extra-fields

I think instead it should generate a java object that has a hashmap as a variable and the following annotated getter and setter methods, similar to this:

public class Datavalue   {
  @JsonProperty("id")
  private String id = null;

  @JsonProperty("source")
  private String source = null;

  @JsonProperty("target")
  private String target = null;

  protected Map<String,String> otherProperties = new HashMap<String,String>();

  public Datavalue id(String id) {
    this.id = id;
    return this;
  }
  @JsonAnyGetter
  public Map<String, String> any() {
   return this.otherProperties;
  }

  @JsonAnySetter
  public void set(String name, String value) {
   this.otherProperties.put(name, value);
  }

as Explained here: http://www.cowtowncoder.com/blog/archives/2011/07/entry_458.html

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.