【发布时间】:2021-12-11 22:19:03
【问题描述】:
请多多包涵。我浏览了很多链接,但找不到适合我的案例的解决方案。我需要帮助。
注意:我无法更改 JSON 请求(在测试中表示为地图)
这是我的 POJO:
public class TestModelWithDoubleField {
private Double frequency;
public Double getFrequency(){
return frequency;
}
/**
* @param frequency the frequency to set
*/
public void setFrequency(Double frequency) {
this.frequency = frequency;
}
/**
* @param frequency the frequency to set
*/
@JsonIgnore
public void setFrequency(Integer frequency) {
if(frequency != null) {
setFrequency(new Double(frequency));
}
}
}
这是失败的测试:
@Test
public void testWithIntegerValueConvertToDoubleFieldInPOJO() throws IOException {
final Map<String, Integer> map = new HashMap<>();
map.put("frequency", 900);
TestModelWithDoubleField pojo = objectMapper.convertValue(map, TestModelWithDoubleField.class);
Assert.assertNotNull(pojo);
Assert.assertNotNull(pojo.getFrequency()); //-> This is giving output as null. Hence fails.
}
在Assert.assertNotNull(pojo.getFrequency()); 行中,频率为空。因此测试失败。
我希望它自动转换为 Double 类型。
将@JsonIgnore 放在另一个设置器上也不起作用。
从该地图中获取有效对象的任何方法都可以。
【问题讨论】:
标签: java spring-boot jackson jackson-databind