我正在制作一个客户端-服务器应用程序,它将矩阵发送到服务器,在服务器中计算其行列式,然后发送回客户端。我制作了这个包装类:
public class MatrixDTO { // with getters and setters
private double[][] matrix;
private double determinant;
}
我还实现了从 MatrixDTO 对象获取行列式的服务器逻辑。 我已在服务器中添加了此 RestController:
@RestController
public class MatrixController {
@RequestMapping(value = "/", method = RequestMethod.POST)
public MatrixDTO postMapping(@RequestParam MatrixDTO matrixDTO) {
// code to compute determinant ommitted
matrixDTO.setDeterminant(determinant);
return matrixDTO;
}
然后在客户端中我添加了发送请求的方法:
final String uri = "http://localhost:8080/?matrixDTO={matrixDTOparam}";
// initialized wrapper object only with matrix data
MatrixDTO input = new MatrixDTO(data);
Map<String, MatrixDTO> params = new HashMap<>();
params.put("matrixDTOparam", input);
RestTemplate restTemplate = new RestTemplate();
result = restTemplate.postForObject(uri, input, MatrixDTO.class, params);
// now I should be able to extract the determinant with result.getDeterminant()
为了让这个简单的代码正常工作,我们花费了很多时间。错误是:
Failed to convert value of type 'java.lang.String' to required type 'MatrixDTO';
nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'MatrixDTO':
no matching editors or conversion strategy found]
我的问题如下:我应该为我的问题选择另一种方法吗?如果没有,是否有一种简单的方法可以使代码正常工作?我正在寻找一个简单的实现,而不需要进行大量配置。谢谢。
最佳答案
到目前为止,我的错误似乎是在 Controller 中使用@RequestParam 而不是@RequestBody。 通过更改它并在客户端中使用此代码:
final String uri = "http://localhost:8080/";
MatrixDTO input = new MatrixDTO(data);
RestTemplate restTemplate = new RestTemplate();
result = restTemplate.postForObject(uri, input, MatrixDTO.class);
它看起来工作得足够好。
关于java - 使用 Spring Web 将自定义对象从客户端传递到 REST 端点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61683159/