Java - 对象映射器 - 要列出的数字的 JSON 数组<Long>

在我的前端,我发送了这个 JSON:


"ids": [ 123421, 15643, 51243],

"user": {

   "name": "John",

   "email": "john@sovfw.com.br" 

}

下面是我的 Spring 端点:


@PostMapping(value = "/sendToOficial")

public ResponseEntity<?> sendToOficial(@RequestBody Map<String, Object> payload) {


ObjectMapper mapper = new ObjectMapper();

List<Long> pointsIds = mapper.convertValue( payload.get("pointsIds"), List.class );

UsuarioDTO autorAlteracao = mapper.convertValue(payload.get("user"), UsuarioDTO.class);


for (Long idPoint : pointsIds) { ... }

但是我收到了一个 Cast Exception,因为它不能将 Integer 转换为 Long。


我无法将“ids”数字接收为整数,我想接收为长整数。请问,我怎么能这样?


缥缈止盈
浏览 192回答 3
3回答

慕哥6287543

首先,定义用于映射请求对象的 POJO:public class RequestObj implements Serializable{&nbsp; &nbsp; private List<Long> ids;&nbsp; &nbsp; private UsuarioDTO user;&nbsp; &nbsp; /* getters and setters here */}public class UsuarioDTO implements Serializable{&nbsp; &nbsp; private String name;&nbsp; &nbsp; private String email;&nbsp; &nbsp; /* getters and setters here */}然后修改您的端点:@PostMapping(value = "/sendToOficial")public ResponseEntity<?> sendToOficial(@RequestBody RequestObj payload) {通过这种方式,您也不需要使用ObjectMapper. 就打电话payload.getIds()。还要考虑这样,如果有效负载发生变化,您只需要更改RequestObj定义,而使用ObjectMapper会强制您以一种重要的方式更新端点。将有效载荷表示与控制逻辑分开会更好也更安全。

LEATH

在jackson-databind-2.6.x及更高版本中,您可以使用配置功能ObjectMapper将低类型int值(适合 32 位的long值)配置为序列化值DeserializationFeature#USE_LONG_FOR_INTS:@PostMapping(value = "/sendToOficial")public ResponseEntity<?> sendToOficial(@RequestBody Map<String, Object> payload) {&nbsp; &nbsp; ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature .USE_LONG_FOR_INTS, true);&nbsp; &nbsp; List<Long> pointsIds = mapper.convertValue( payload.get("pointsIds"), List.class );&nbsp; &nbsp; UsuarioDTO autorAlteracao = mapper.convertValue(payload.get("user"), UsuarioDTO.class);&nbsp; &nbsp; for (Long idPoint : pointsIds) { // ... }}

哈士奇WWW

如果您只想让映射器读入List<Long>,请使用此技巧通过子类化获取完整的泛型类型信息。例子ObjectMapper mapper = new ObjectMapper();List<Long>listOfLong=mapper.readValue("[ 123421, 15643, 51243]" ,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new TypeReference<List<Long>>() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });System.out.println(listOfLong);印刷[123421, 15643, 51243]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java