我有一个 DTO
public class FilterSet {
@JsonProperty("price")
private IntervalFilter<Double> priceFilter;
public IntervalFilter<Double> getPriceFilter() {
return priceFilter;
}
public void setPriceFilter(IntervalFilter<Double> priceFilter) {
this.priceFilter = priceFilter;
}
public static class IntervalFilter<T> {
private IntervalValue<T> value;
public IntervalValue<T> getValue() {
return value;
}
public void setValue(IntervalValue value) {
this.value = value;
}
public static class IntervalValue<T> {
private T from;
private T to;
public T getFrom() {
return from;
}
public void setFrom(T from) {
this.from = from;
}
public T getTo() {
return to;
}
public void setTo(T to) {
this.to = to;
}
}
}
}
当我发送 PriceFilter {"price": { "value": { "from": 1.1, "to": 1.2 } } } 就可以了。 当我发送 PriceFilter {"price": { "value": { "from": 1.0, "to": 2.0 } } } 并尝试获取 Double 值时:
Double priceFrom = priceFilter.getValue().getFrom();
我看到 java.lang.ClassCastException: java.lang.Integer 无法转换为 java.lang.Double
我做错了什么?
更多信息: Json: {"price":{ "value": { "from": 1.0, "to": 2.1 } } }
我有一个来自 Spring Controller 的 FilterSet 对象。在那里我可以看到一个字段“priceFilter”(IntervalFilter 类型),其中包含字段“value”(IntervalValue 类型)和字段“from”(Integer 类型)和“to”(Double 类型)。
public String getLinks(
@RequestBody FilterSet filterData
) {
...
}
最佳答案
可以使用以下 JSON(使用整数)重现该错误。
{"price":{ "value" : { "from" : 1, "to" : 2.1 } } }
为了避免这个问题,所有引用 IntervalValue
必须使用泛型类型进行声明(即使用 ´<> ), otherwise the raw type is used and it will be considered to be an
Integer in the example above (which causes the
ClassCastException ). When you instead use the generic type, a value of type
Double` 是强制的,因为它是在代码中声明的。因此,如果将 setter 更改为以下内容,则它的工作方式如下预计:
public void setValue(IntervalValue<T> value) {
this.value = value;
}
请注意,该参数的类型为 IntervalValue<T>
,不是IntervalValue
如原始代码所示。
关于java - jackson .当值从泛型类获取时出现 ClassCastException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27656832/