[英]deserialise the list of integer from json to java using Jackson Object Mapper
[英]Java - Object Mapper - JSON Array of Number to List<Long>
在我的前端,我发送这个JSON:
"ids": [ 123421, 15643, 51243],
"user": {
"name": "John",
"email": "john@sovfw.com.br"
}
到我的Spring Endpoint:
@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”数字,我希望收到Long。 拜托,我怎么能这样做?
首先,定义POJO以映射您的请求对象:
public class RequestObj implements Serializable{
private List<Long> ids;
private UsuarioDTO user;
/* getters and setters here */
}
public class UsuarioDTO implements Serializable{
private String name;
private String email;
/* getters and setters here */
}
然后修改您的端点:
@PostMapping(value = "/sendToOficial")
public ResponseEntity<?> sendToOficial(@RequestBody RequestObj payload) {
这样您也不需要使用ObjectMapper
。 只需调用payload.getIds()
。
还要考虑这样,如果有效负载发生变化,您只需要更改RequestObj
定义,而使用ObjectMapper
会强制您以一种重要的方式更新您的终端。 将有效负载表示与控制逻辑分开会更好,更安全。
在jackson-databind-2.6.x及更高版本中,您可以使用DeserializationFeature#USE_LONG_FOR_INTS
配置功能将ObjectMapper
配置为将低类型int
值(适合32位的值) DeserializationFeature#USE_LONG_FOR_INTS
化为long
值:
@PostMapping(value = "/sendToOficial")
public ResponseEntity<?> sendToOficial(@RequestBody Map<String, Object> payload) {
ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature .USE_LONG_FOR_INTS, true);
List<Long> pointsIds = mapper.convertValue( payload.get("pointsIds"), List.class );
UsuarioDTO autorAlteracao = mapper.convertValue(payload.get("user"), UsuarioDTO.class);
for (Long idPoint : pointsIds) { // ... }
}
如果您只是希望映射器读入List<Long>
,请使用此技巧通过子类化获取完整的泛型类型信息。
例
ObjectMapper mapper = new ObjectMapper();
List<Long>listOfLong=mapper.readValue("[ 123421, 15643, 51243]" ,
new TypeReference<List<Long>>() {
});
System.out.println(listOfLong);
打印
[123421, 15643, 51243]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.