Rest模板ResponseEntity主体正在更改变量的类型,如何控制类型?

问题描述 投票:0回答:1

我正在从具有以下条件的应用发出发布请求

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

问题是,返回的地图没有作为BigDecimal值的数量,当我在responseMap.getbody()中看到它们时,这些BigDecimal值将自动转换为Integer。

[请帮助我了解如何将其保持为BigDecimal值。

此外,实际代码比上面的代码稍微复杂一些,但我想保持简单。我绝对希望将值保留为BigDecimal,只是不确定如何。

java rest http spring-restcontroller
1个回答
0
投票

您可能正在使用Jackson作为RestTemplate的前进库。

读取值时,ObjectMapper读取数字为整数/双精度等。您可以使用以下配置属性轻松设置反序列化的行为。

jackson-databind DeserializationFeature

USE_BIG_DECIMAL_FOR_FLOATS

[如果只有通用类型描述(对象或数字,或在无类型的Map或Collection上下文中),则确定是否将JSON浮点数反序列化为BigDecimals的功能。

USE_BIG_INTEGER_FOR_INTS

[如果只有通用类型描述(对象或数字,或者在无类型的Map或Collection上下文中,则可确定是否将JSON整数(非浮点数)数字反序列化为BigIntegers的功能。

要进行设置,您可以按照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)注释。

在其他进阶库(例如Gson)中也可以使用类似的技术

© www.soinside.com 2019 - 2024. All rights reserved.