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 并將其分配給字節數組。

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),則可以采用這種方法。
添加回答
舉報