【问题标题】:Deserializing JSON to polymorphic object model using @JsonTypeInfo & @JsonSubTypes not working?使用 @JsonTypeInfo 和 @JsonSubTypes 将 JSON 反序列化为多态对象模型不起作用?
【发布时间】:2017-04-22 14:36:01
【问题描述】:

我正在尝试让 REST 端点在 POST 时创建 Widget 的子类型,

这里是所有Widgets 的基类

@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 {
...
}

这是WidgetType 枚举:

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";
    }
}

这是我的 Spring 端点:

@RequestMapping(method = RequestMethod.POST)
public Optional<Widget> createWidget(@Valid final Widget widget) {
    ...
    }

当到达那个端点时,它会抛出这个异常:

{
  "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": "...."
}

浏览我的问题的几个解决方案,我可能必须手动注册子类型,我可能错了,但我认为必须有办法让它与注释一起工作,也许我错过了什么?

【问题讨论】:

    标签: java json spring jackson


    【解决方案1】:

    问题解决了, 我正在用杰克逊注释来注释我的课程,却忘记了我正在发送多部分 POST 请求,这甚至不会发送给杰克逊。 解决方法就这么简单:

    @RequestMapping(method = RequestMethod.POST)
    public Optional<Widget> createWidget(@RequestBody final Widget widget) {
        ...
        }
    

    【讨论】:

      猜你喜欢
      • 2013-10-14
      • 1970-01-01
      • 1970-01-01
      • 2021-06-25
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      • 2020-12-02
      • 2023-03-31
      相关资源
      最近更新 更多