泛型抽象类的自定义Jackson反序列化

92dk7w1h  于 2022-11-08  发布在  其他
关注(0)|答案(2)|浏览(297)

我在尝试反序列化以下类时遇到问题:

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的具体类:
整数度量值D至:

public class IntMetricValueDto extends MetricValueDto<Integer> {

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

浮动度量值D至:

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.resson.dto.MetricValueDto的示例构造为:抽象类型需要Map到具体类型,具有自定义反序列化程序,或者包含其他类型信息
数据收集事件日期至:

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

我基本上已经尝试了网上的一切,我不能使它工作;任何建议都是有益。

wydwbb8l

wydwbb8l1#

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;
    ...
}
js4nwp54

js4nwp542#

JsonTypeInfo可以工作,并将特定于实现的细节添加到响应中,这在以后可能会给API客户端带来混乱。
我最终实现了一个自定义的StdDeserializer

public class MetricValueDtoDeserializer<T> extends StdDeserializer<MetricValueDto<T>> {

    private static final long serialVersionUID = 1L;

    public MetricValueDtoDeserializer() {
        this(null);
    }

    public MetricValueDtoDeserializer(Class<?> vc) {
        super(vc);
    }

    private ObjectMapper mapper;

    @Override
    public MetricValueDto<T> deserialize(JsonParser jsonParser, DeserializationContext context)
            throws IOException, JsonProcessingException {
        String metricType = jsonParser.getCurrentName();
        mapper = (ObjectMapper) jsonParser.getCodec();
        ObjectNode objectNode = (ObjectNode) mapper.readTree(jsonParser);
        Iterator<Entry<String, JsonNode>> elementsIterator = objectNode.fields();
        Number number = null;
        while (elementsIterator.hasNext()) {
            Entry<String, JsonNode> element = elementsIterator.next();
            String key = element.getKey();
            if (key.equals("value")) {
                number = parseValue(element, metricType);
            }
            if (key.equals("trend")) {
                MetricTrend metricTrend = parseTrend(element);
                return (produceMetricValueDto(number, metricTrend));
            }
        }
        throw new IOException();
    }

    @SuppressWarnings("unchecked")
    private MetricValueDto<T> produceMetricValueDto(Number number, MetricTrend metricTrend) throws IOException {
        if (number instanceof Integer) {
            return (MetricValueDto<T>) new IntMetricValueDto((Integer) number, metricTrend);
        } else if (number instanceof Float) {
            return (MetricValueDto<T>) new FloatMetricValueDto((Float) number, metricTrend);
        }
        throw new IOException();
    }

    private MetricTrend parseTrend(Entry<String, JsonNode> element)
            throws JsonProcessingException {
        String trend = mapper.treeToValue(element.getValue(), String.class);
        if (trend == null) {
            return null;
        } else {
            return MetricTrend.valueOf(trend);
        }
    }

    private Number parseValue(Entry<String, JsonNode> element, String metricType)
            throws IOException {
        if (metricType.equals(MetricType.CANOPY_COVERAGE.toValue())
                || metricType.equals(MetricType.PLANT_SIZE.toValue())) {
            return mapper.treeToValue(element.getValue(), Float.class);
        } else if (metricType.equals(MetricType.INSECT_COUNT.toValue())
                || metricType.equals(MetricType.PLANT_COUNT.toValue())) {
            return mapper.treeToValue(element.getValue(), Integer.class);
        }
        throw new IOException();
    }
}

代码最终变得比JsonTypeInfo更复杂,但是API客户端不知道特定于实现的细节。

相关问题