英文:
compare Set<Long> that contains integers to Set<Long>
问题
我有一个控制器,在其响应体中返回了一个 Set<Long>
:
public ResponseEntity<?> getIds(){
Set<Long> ids = someFunc(..);
return ResponseEntity.ok(ids);
}
在我的测试中,我试图比较REST调用的结果与不同的 Set<Long>
:
MockHttpServletResponse result = mockMvc.perform(.....).andReturn().getResponse();
Set<Long> responseBody = objectMapper.readValue(result.getContentAsByteArray(), Set.class);
responseBody = responseBody.stream().map(number->number.longValue()).collect(Collectors.toSet());
assertThat(responseBody.equals(otherSet),is(true));
当我以调试模式运行代码时,我发现 responseBody 包含整数对象。
在映射的那一行出现的错误 (map(number->number.longValue())
):
java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.Long (java.lang.Integer and java.lang.Long are in module java.base of loader 'bootstrap')
看起来对象映射器将 Long 对象 (ids) 转换为整数对象,因为它可以适应整数。
我知道我可以使用:
new ObjectMapper().configure(DeserializationFeature.USE_LONG_FOR_INTS,true);
但我想找到一个将值转换而不对我的映射器添加约束的解决方案。
英文:
I have a controller that returns a Set<Long>
in its response`s body :
public ResponseEntity<?> getIds(){
Set<Long> ids = someFunc(..);
return ResponseEntity.ok(ids);
}
In my test I'm trying to compare the result of the rest call to a different Set<Long>
MockHttpServletResponse result = mockMvc.perform(.....).andReturn().getResponse();
Set<Long> responseBody = objectMapper.readValue(result.getContentAsByteArray(), Set.class);
responseBody = responseBody.stream().map(number->number.longValue()).collect(Collectors.toSet());
assertThat(responseBody.equals(otherSet),is(true));
When I run the code in debug mode I saw that the responseBody contains Integer objects.
The error that I'm getting on the line with the mapping (map(number->number.longValue())
) :
java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.Long (java.lang.Integer and java.lang.Long are in module java.base of loader 'bootstrap')
It seems that the object mapper convert the Long objects (ids) to Integer objects because it can fit into an integer..
I know that I can use :
new ObjectMapper().configure(DeserializationFeature.USE_LONG_FOR_INTS,true);
but I want to find a solution that will convert the value and not add a constraint on my mapper.
答案1
得分: 1
你可以将你的数据读取为 Set<Long>
。使用 TypeReference
来指定你想要读取的类型,这样你就不需要将 Integer
转换为 Long
。
Set<Long> responseBody = objectMapper.readValue(result.getContentAsByteArray(),
new TypeReference<Set<Long>>(){});
英文:
You can read your data as Set<Long>
. Use TypeReference
to specify the type you want to read, then you don't need to convert Integer
into Long
Set<Long> responseBody = objectMapper.readValue(result.getContentAsByteArray(),
new TypeReference<Set<Long>>(){});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论