Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swagger isn't smart enough to handle anonymous types (such as maps)

I'm using enunciate to generate Swagger documentation for a REST API. One of my legacy beans contains a Map, and Swagger complains about this:

[INFO] --- maven-enunciate-plugin:1.27:docs (default) @ foo-api ---
[INFO] initializing enunciate.
[INFO] invoking enunciate:generate step...
[WARNING] Validation result has errors.
/.../rest/BarBean.java:170: [swagger] Swagger isn't smart enough to handle anonymous types (such as maps).
   public HashMap<String, BazBean> getBazBeans() {

Are there any annotations I can drop into the bean class so that Swagger can handle this?

Barring that, is there a way to tell Swagger to simply ignore the field or the whole class? I know that Swagger ignores classes without the @XmlRootElement annotation, but BazBean is tragically used in another endpoint that accepts XML.

like image 714
Josh Glover Avatar asked Nov 18 '13 09:11

Josh Glover


1 Answers

I can think of two ways to get around the problem:

  1. Exclude the legacy class BarBean from your enunciate maven configuration
  2. Add a @XmlJavaTypeAdapter annotation to the BarBean#getBazBeans() method

I will describe the second solution in more detail, because the first is well known. The return type of getBazBeans() is an anonymous type, meaning that it's not declared in your project. You can change this with an javax.xml.bind.annotation.adapters.XmlAdapter, connecting it to the getBazBeans() methods return type via the javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter annotation

import import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
public class BarBean {

  @XmlJavaTypeAdapter( BazBeansAdapter.class )
  Map<String, BazBean> getBazBeans() { /* ... */ }

}

public class BazBeansAdapter extends XmlAdapter<BazBeansContainer, Map<String, BayBean>> {

  /*
  Your implementation of serialization and deserialization. 
  Usually creating and reading the container object. 
  */

}


public class BazBeansContainer {

  private Map<String, BayBean> beans;    

  /* Getter, Setter, etc. */

}
like image 120
uvpoblotzki Avatar answered Oct 17 '22 10:10

uvpoblotzki