我正在从具有以下内容的应用程序发出发布请求
Set<Accounts> set = populateAccounts();
ResponseEntity<Map> responseMap =
restTemplate.postForEntity("http://localhost:8080/maptest", set, Map.class);
return responseMap.getBody();
然后这个请求从responseMap.getBody()返回一个Map;
下面是我收到帖子请求的代码
@PostMapping("/maptest")
public ResponseEntity<Map> mapReturn(@RequestBody Set<Accounts> accounts) {
HashMap<String, Amount> map = new HashMap<String, String>();
map.put("account1", new Amount(BigDecimal.TEN));
map.put("account2", new Amount(BigDecimal.ZERO));
return ResponseEntity.ok(map);
}
问题是,返回的 Map 没有 BigDecimal 值的金额,当我在 responseMap.getbody() 中看到这些 BigDecimal 值时,它们会自动转换为整数;
请帮助我了解如何将它们维护为 BigDecimal 值。
另外,实际的代码比上面的稍微复杂一些,但我想保持简单。我绝对想将值保留为 BigDecimal,只是不知道如何。
最佳答案
您可能正在使用 Jackson 作为 RestTemplate 的游行库。
当您读取值时,ObjectMapper
将数字读取为整数/ double 等。
您可以使用以下配置属性轻松设置反序列化行为。
jackson-databind DeserializationFeature
USE_BIG_DECIMAL_FOR_FLOATS
Feature that determines whether JSON floating point numbers are to be deserialized into BigDecimals if only generic type description (either Object or Number, or within untyped Map or Collection context) is available.
USE_BIG_INTEGER_FOR_INTS
Feature that determines whether JSON integral (non-floating-point) numbers are to be deserialized into BigIntegers if only generic type description (either Object or Number, or within untyped Map or Collection context) is available.
要设置它,您可以按照描述编写 here
ObjectReader r = objectMapper.reader(MyType.class);
// enable one feature, disable another
MyType value = r
.with(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)
.without(DeserializationFeature.WRAP_EXCEPTIONS)
.readValue(source);
或者只是
ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);
OptionTransaction transaction = mapper.readValue(jsonString, OptionTransaction.class);
你当然可以自己写number deserializers并使用 @JsonDeserialize(using = CustomNumberDeserializer.class)
注释。
类似的技术在其他 marhalling 库(如 Gson)中也是可行的
关于java - Rest模板ResponseEntity主体正在改变变量的类型,如何控制类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62292807/