java - 在spring中将JSON数组字段恢复为字节数组
问题描述
我是 spring 新手,在这里我发送一个 http 请求,需要将消息传递给服务器。但是消息应该作为字节数组发送。我使用以下 curl 命令。这里传递的消息是“你好”。
curl -i -H "Content-type: application/json" -X POST -d '{"message":[72,69,76,76,79]}' http://localhost:8080/json
控制器应该监听请求并再次将消息字段恢复为 byte[]。控制器代码:
@RequestMapping(value = "/json", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public 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]
解决方案
当您将请求正文作为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),那就是这样做的方法。
推荐阅读
- powershell - New-WebApplication 在 powershell 的物理路径参数中使用网络路径失败
- python-3.x - 如何使用带有 discord.py 的 gmail API 每分钟在聊天中将 10 封最近的未读电子邮件作为单独的消息发送?
- ngrx - @ngrx/store 要求安装 @angular/core@^10.0.0 但是我们有 "@angular/core": "^11.0.5"
- migration - 尝试将问题从 JIRA 导入到 Redmine
- python - 拆分功能的python替代解决方案
- php - 组装菜单(节点树),其中只有父节点是已知的
- shell - 如何在 UNIX shell 脚本中引用通用脚本中的变量和文件中的变量名
- python - 在python中将一个列表分成两个单独的列表
- excel - 在 Excel 的单元格 C1 中,如何从单元格 B1 的逗号分隔值列表中选择未在 A 列中以逗号分隔的单元格/值?
- python - 如何使用 NLP 从 PDF 文件中提取关键字及其页码?