gpt4 book ai didi

java - 将 JSON 从 React 传递到 Spring Controller

转载 作者:行者123 更新时间:2023-11-30 06:22:11 27 4
gpt4 key购买 nike

所以我尝试使用 fetch 发送一些数据。

console.log(results.data);

results.data是我想发送的内容。上面的代码在控制台中给出了以下内容:

[Array[52], Array[52], Array[52], Array[52], Array[52], Array[52], Array[52], Array[52], Array[52], Array[52], Array[52], Array[52], Array[52], Array[52], Array[52], Array[1]]

这让我相信我应该期待 String[][]在 Controller 中

这是 react 代码:

fetch('/device', {
method: 'post',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify({data : results.data})
}).then(res=>res.json())
.then(res => console.log(res));

和 Controller :

@RequestMapping(value= "/deviceIngestion", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody String deviceIngestion (@RequestParam(value = "data[][]") String[][] data) {

return data [0][0];
}

但我在控制台中收到此响应:

Resolved exception caused by Handler execution: org.springframework.web.bind.MissingServletRequestParameterException: Required String[][] parameter 'data[][]' is not present

在尝试其他一些操作后,我也遇到了此错误:

"Could not read document: Can not deserialize instance of java.lang.String[][] out of START_OBJECT token↵ at [Source: java.io.PushbackInputStream@2f36dd94; line: 1, column: 1]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String[][] out of START_OBJECT token↵ at [Source: java.io.PushbackInputStream@2f36dd94; line: 1, column: 1]" path : "/deviceIngestion" status : 400 timestamp : 1513693466676 Name

我还尝试使用 ArrayList<String[]> 创建一个类在构造函数中替换 String[][]我在 Controller 中使用但没有运气。

任何帮助将不胜感激,谢谢

最佳答案

问题似乎是 Java 无法理解 JSON 的格式,即: [[x,y],[a,b]]为了解决这个问题,我将 JSON 更改为对象数组[{x:x, y:y},{x:a,y:b}] see this

之后,我创建了一个与存储在 JSON 数组中的对象相匹配的 Java 类,并将 Controller 更改为以下内容:

@PostMapping("/device")
public String deviceIngestion (@RequestBody List<DeviceData> devices) throws IOException{
return "success";
}

关于java - 将 JSON 从 React 传递到 Spring Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47891105/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com