关于 java:Map to Map<String, Integer> from restTemplate
Map to Map<String, Integer> from restTemplate
本问题已经有最佳答案,请猛点这里访问。
我调用restTemplate 并接收rawMap。从调试中我看到键类和值类是字符串。没关系,因为响应我的 restTemplate 的服务以 JSON 格式发送地图。现在我想用这个代码创建地图:
|
1
2 |
Map<String, Integer> gameIdsMap = new HashMap<>();
rawGameIdsMap.forEach(((key, value) -> gameIdsMap.put(String.valueOf(key), Integer.parseInt(String.valueOf(value))))); |
我很好奇。有没有更有效和更清晰的方法来做到这一点?
我不能只从 restTemplate
接收
rest模板
|
1
|
Map rawGameIdsMap = Objects.requireNonNull(restTemplate.getForObject(uriFactory.getReverseGameIdsURI(), Map.class));
|
相关讨论
- 我不确定,但类似的东西可能会起作用
Map<String, Integer> casted = raw.parallelStream().map(Map::put); - stackoverflow.com/questions/8108887/…
它允许将
所以你可以做类似的事情:
|
1
2 3 |
Map<String, String> gameIdsMap = Objects.requireNonNull(
template.exchange(uri, HttpMethod.GET, null, new ParameterizedTypeReference<Map<String, String>>() { }).getBody()); |
这样做:
|
1
2 3 |
Map<String, Integer> gameIdsMap= Objects.requireNonNull(
template.exchange(uri, HttpMethod.GET, null, new ParameterizedTypeReference<Map<String, Integer>>() { }).getBody()); |
也是正确的(至少对于 Jackson),但如果该值无法转换为
相关讨论
- @Sotirios Delimanolis 你有杰克逊/格森的参考资料或一个具体的例子来证明这样的事情吗?抱歉,现在没时间写真正的测试。
-
我对 Spring 模板的
exchange() 的最后一个有疑问。我会试一试。 - @Sotirios Delimanolis 我检查过了。它像你说的那样工作。至少与杰克逊在一起。我会删除我的答案,但不能因为它被接受。我至少更新了以符合现实。
THE END
二维码