使用SpringWeb将自定义对象从客户端传递到REST端点



我正在制作一个客户端-服务器应用程序,该应用程序将矩阵发送到服务器,在服务器中计算其行列式,然后将其发送回客户端。我制作了这个包装类:

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]

我的问题是:我应该为我的问题选择另一种方法吗?如果不是,有没有一种简单的方法可以让代码工作?我正在寻找一个简单的实现,而不是需要做很多配置。谢谢

到目前为止,我的错误似乎是在控制器中使用@RequestParam而不是@RequestBody。通过更改并在客户端中使用此代码:

final String uri = "http://localhost:8080/";
MatrixDTO input = new MatrixDTO(data);
RestTemplate restTemplate = new RestTemplate();
result = restTemplate.postForObject(uri, input, MatrixDTO.class);

它似乎运行得很好。

最新更新