Skip to content

Instantly share code, notes, and snippets.

@fehguy
Created February 27, 2016 01:22
Show Gist options
  • Save fehguy/00fa199128876a5f5afb to your computer and use it in GitHub Desktop.
Save fehguy/00fa199128876a5f5afb to your computer and use it in GitHub Desktop.
override example
package io.swagger.model.override;
import com.fasterxml.jackson.databind.JavaType;
import io.swagger.converter.ModelConverter;
import io.swagger.converter.ModelConverterContext;
import io.swagger.models.Model;
import io.swagger.models.properties.*;
import io.swagger.util.Json;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.Iterator;
/**
* Sample converter implementation which turns "MyCustomClass" into a DateTime property
*/
public class SamplePropertyConverter implements ModelConverter {
@Override
public Property resolveProperty(Type type, ModelConverterContext context, Annotation[] annotations, Iterator<ModelConverter> chain) {
JavaType _type = Json.mapper().constructType(type);
if (_type != null) {
Class<?> cls = _type.getRawClass();
if (java.util.Date.class.isAssignableFrom(cls)) {
return new LongProperty();
}
}
if (chain.hasNext()) {
return chain.next().resolveProperty(type, context, annotations, chain);
} else {
return null;
}
}
@Override
public Model resolve(Type type, ModelConverterContext context, Iterator<ModelConverter> chain) {
if (chain.hasNext()) {
return chain.next().resolve(type, context, chain);
} else {
return null;
}
}
}
@fehguy
Copy link
Author

fehguy commented Feb 27, 2016

testing with this:

        ModelConverters.getInstance().addConverter(new SamplePropertyConverter());
        final Map<String, Model> model = ModelConverters.getInstance().read(MyPojo.class);
        Json.prettyPrint(model);

and this pojo:

    public static class MyPojo {
        public String getId() {
            return "";
        }

        public void setId(String id) {
        }

        @ApiModelProperty(value = "instead of modeling this class in the documentation, we will model a string")
        public MyCustomClass getMyCustomClass() {
            return null;
        }

        public void setMyCustomClass(MyCustomClass myCustomClass) {
        }

        public java.util.Date getDate() {
            return null;
        }
    }

Does the right thing:

{
  "MyPojo" : {
    "type" : "object",
    "properties" : {
      "id" : {
        "type" : "string"
      },
      "myCustomClass" : {
        "description" : "instead of modeling this class in the documentation, we will model a string",
        "$ref" : "#/definitions/MyCustomClass"
      },
      "date" : {
        "type" : "integer",
        "format" : "int64"
      }
    }
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment