首页 > 解决方案 > 在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]

标签: javaspring

解决方案


当您将请求正文作为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),那就是这样做的方法。


推荐阅读