gpt4 book ai didi

java - 使用 @JsonTypeInfo 和 @JsonSubTypes 将 JSON 反序列化为多态对象模型不起作用?

转载 作者:行者123 更新时间:2023-12-02 02:52:45 33 4
gpt4 key购买 nike

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

这是所有Widget的基类

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

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

最佳答案

问题已解决,我用 Jackson 注释对我的类进行注释,却忘记了我正在发送多部分 POST 请求,这甚至不会发给 Jackson。解决方案很简单:

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

关于java - 使用 @JsonTypeInfo 和 @JsonSubTypes 将 JSON 反序列化为多态对象模型不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43560427/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com