Reputation: 574
I am trying to have a REST endpoint create a subtype of Widget
when POST
ing to it,
here is the base class for all Widget
s
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "widgetType")
@JsonSubTypes({
@JsonSubTypes.Type(value = TextWidget.class, name = WidgetType.Constants.TEXT),
@JsonSubTypes.Type(value = ImageWidget.class, name = WidgetType.Constants.IMAGE),
@JsonSubTypes.Type(value = IndicatorWidget.class, name = WidgetType.Constants.INDICATOR),
@JsonSubTypes.Type(value = MapWidget.class, name = WidgetType.Constants.MAP),
@JsonSubTypes.Type(value = ChartWidget.class, name = WidgetType.Constants.CHART)
})
@Data
@Slf4j
public abstract class Widget {
...
}
this is the WidgetType
enum:
public enum WidgetType {
TEXT(Constants.TEXT),
IMAGE(Constants.IMAGE),
INDICATOR(Constants.INDICATOR),
MAP(Constants.MAP),
CHART(Constants.CHART);
private final String type;
WidgetType(final String type) {
this.type = type;
}
public static class Constants {
public static final String TEXT = "TEXT";
public static final String IMAGE = "IMAGE";
public static final String INDICATOR = "INDICATOR";
public static final String MAP = "MAP";
public static final String CHART = "CHART";
}
}
and this is my Spring endpoint:
@RequestMapping(method = RequestMethod.POST)
public Optional<Widget> createWidget(@Valid final Widget widget) {
...
}
when hitting that endpoint it throws this exception:
{
"timestamp": 1493029336774,
"status": 500,
"error": "Internal Server Error",
"exception": "org.springframework.beans.BeanInstantiationException",
"message": "Failed to instantiate [....models.Widget]: Is it an abstract class?; nested exception is java.lang.InstantiationException",
"path": "...."
}
skimming through few solutions for my problem, I might have to manually register the subtypes, I might be wrong, but I think there must be a way to make it work with annotations, maybe I am missing something?
Upvotes: 2
Views: 819
Reputation: 574
problem solved, I was annotating my classes with Jackson annotation and forgot that I was sending multipart POST requests, that wasn't even going to Jackson. The solution is as simple as this:
@RequestMapping(method = RequestMethod.POST)
public Optional<Widget> createWidget(@RequestBody final Widget widget) {
...
}
Upvotes: 3