簡體   English   中英

Java - Object Mapper - 要列出的數字的JSON數組<Long>

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM