Skip to content

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

@pumpadump

Description

@pumpadump
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

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions