亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 spring 中將 JSON 數組字段恢復為字節數組

在 spring 中將 JSON 數組字段恢復為字節數組

胡子哥哥 2023-08-09 15:13:39
我是 spring 新手,在這里我發送一個 http 請求,需要將消息傳遞到服務器。但消息應該作為字節數組發送。我使用以下curl命令。這里傳遞的消息是“hello”。curl -i -H "Content-type: application/json" -X POST -d '{"message":[72,69,76,76,79]}' http://localhost:8080/json控制器應該監聽請求并再次將消息字段恢復為 byte[]??刂破鞔a:@RequestMapping(value = "/json", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)@ResponseBodypublic ResponseEntity<Map<String, Object>> jsonReceiver(@RequestHeader Map<String, String> headers, @RequestBody Map<String, Object> request) {    String bytes = request.get("message").toString();    LOGGER.info("Message: {}", bytes);    Map<String, Object> response = new HashMap<>();    response.put("status-code", "1000");    response.put("success", "true");    HttpHeaders respHeaders = new HttpHeaders();    respHeaders.add("Pragma", "ack");    return new ResponseEntity<Map<String, Object>>(response, respHeaders, HttpStatus.ACCEPTED);}在這里我可以獲得字符串形式的輸出。但我想把它變成一個字節[]。有什么方法可以從控制器獲取字節數組,而不需要讀取字符串然后對其進行操作。Message: [72,69,76,76,79]
查看完整描述

3 回答

?
瀟湘沐

TA貢獻1816條經驗 獲得超6個贊

嘗試這個:


String message  = "[72,69,76,76,79]";

String[] stringArray = message.replaceAll("\\[", "").replaceAll("\\]", "").replaceAll("\\s", "").split(",");

byte[] byteArray = new byte[stringArray.length];


for(int i = 0; i<stringArray.length; i++)

{

    byteArray[i] = (byte) Integer.parseInt(stringArray[i]);

}

首先,轉換為字符串數組。然后,您在該數組中進行迭代,并將每個元素轉換為 int,然后轉換為 byte 并將其分配給字節數組。


查看完整回答
反對 回復 2023-08-09
?
揚帆大魚

TA貢獻1799條經驗 獲得超9個贊

當您獲取請求正文時,Map<String, Object>獲取字節數組的唯一方法是解析“stringyfied”字節數組并構建結果字節數組。


就像是:


String byteArrayAsStr = request.get("message").toString();


// First get only the "string-numeric" values (storing them into a String[]

String[] byteValues = byteArrayAsStr.substring(1, byteArrayAsStr.length() - 1).split(",");

byte[] messageBytes = new byte[byteValues.length];


// then we store each parsed byte value into our result byte[] (messageBytes)

for (int i=0, len=messageBytes.length; i<len; i++) {

   messageBytes[i] = Byte.parseByte(byteValues[i].trim()); // trim not necessary in your case, as you send your array without spaces after commas 

}

[...]

如果您找不到更好的方法來直接以所需類型獲取請求正文(使用適當的 DTO),則可以采用這種方法。


查看完整回答
反對 回復 2023-08-09
?
拉莫斯之舞

TA貢獻1820條經驗 獲得超10個贊

你可以byte[]這樣制作String

byte[] byteArray = bytes.getBytes();


查看完整回答
反對 回復 2023-08-09
  • 3 回答
  • 0 關注
  • 199 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號