尝试反序列化以下课程时遇到问题:

public class MetricValuesDto {

    private Map<MetricType, MetricValueDto<?>> metricValues;

    public MetricValuesDto() {
    }

    public MetricValuesDto(Map<MetricType, MetricValueDto<?>> metricValues) {
        this.metricValues = metricValues;
    }

    public Map<MetricType, MetricValueDto<?>> getMetricValues() {
        return metricValues;
    }

    public void setMetricValues(Map<MetricType, MetricValueDto<?>> metricValues) {
        this.metricValues = metricValues;
    }
}

我的通用抽象类:
public abstract class MetricValueDto<T> {

    private T value;
    private MetricTrend trend;

    public MetricValueDto(T value, MetricTrend trend) {
        this.value = value;
        this.trend = trend;
    }

    public T getValue() {
        return value;
    }

    public void setValue(T value) {
        this.value = value;
    }

    public MetricTrend getTrend() {
        return trend;
    }

    public void setTrend(MetricTrend trend) {
        this.trend = trend;
    }
}

我有两个实现MetricValueDto的具体类:

IntMetricValueDto:
public class IntMetricValueDto extends MetricValueDto<Integer> {

    public IntMetricValueDto(Integer value, MetricTrend trend) {
        super(value, trend);
    }
}

FloatMetricValueDto:
public class FloatMetricValueDto extends MetricValueDto<Float> {

    public FloatMetricValueDto(Float value, MetricTrend trend) {
        super(value, trend);
    }
}

关于将MetricValueDto反序列化的正确策略的任何想法,以便我可以通过ObjectMapperRestTemplate解析吗?每当我跑步时:
restTemplate.exchange("myEndpoint", HttpMethod.GET, entity, DataCollectionEventDto.class);

我懂了

引起原因:com.fasterxml.jackson.databind.JsonMappingException:无法构造com.resson.dto.MetricValueDto的实例:抽象类型要么需要映射到具体类型,要么具有自定义反序列化器,或者包含其他类型信息

DataCollectionEventDto:
public class DataCollectionEventDto {

    private List<MapLayerDto> mapLayers;

    @JsonUnwrapped
    private MetricValuesDto metricValues;

    public List<MapLayerDto> getMapLayers() {
        return mapLayers;
    }

    public void setMapLayers(List<MapLayerDto> mapLayers) {
        this.mapLayers = mapLayers;
    }

    public MetricValuesDto getMetricValues() {
        return metricValues;
    }

    public void setMetricValues(MetricValuesDto metricValues) {
        this.metricValues = metricValues;
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }
}

我基本上已经尝试了网络上的所有内容,但无法正常工作。任何建议都会有所帮助。

最佳答案

JsonSubTypes 批注与 JsonTypeInfo 一起使用以指示子类型。 属性属性 JsonTypeInfo 用于区分不同的子类。

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "typ")
@JsonSubTypes({
        @JsonSubTypes.Type(value = IntMetricValueDto.class, name = "INT"),
        @JsonSubTypes.Type(value = FloatMetricValueDto.class, name = "FLT")}
public abstract class MetricValueDto<T> {

    private T value;
    private MetricTrend trend;
    ...
}

10-04 17:21