gpt4 book ai didi

java - Spring Rest Controller @RequestBody 用于除类之外的接口(interface)

转载 作者:行者123 更新时间:2023-12-02 02:17:57 28 4
gpt4 key购买 nike

我使用带有 POST 请求方法的 Spring Boot Rest Controller ,具有 url (/add) 来保存 JSON 对象,但是在 RequestBody 中它接受接口(interface),除了类(class)

Controller 中的方法:(IVehicle 是一个接口(interface))

@CrossOrigin 
@RequestMapping(value = "/add", method = RequestMethod.POST)
public ResponseEntity<IVehicle> addVehicle(@RequestBody IVehicle vehicle) {

vehicleService.addVehicle(vehicle);
return new ResponseEntity<IVehicle>(vehicleHttpStatus.CREATED);

}

注意:IVehicle是一个接口(interface)。

JSON 对象通过 AngularJS 传递:

$http({

method : 'POST',
url : '../localhost/vehicle/add',
data : $scope.vehicle,
dataType : 'json',
headers : {'Content-Type' : 'application/json; charset=utf-8'}

}).then(function(response) {
console.log( response );

}, function(error) {
console.log( error );

});

ERROR [nio-8080-exec-5] .w.s.m.s.DefaultHandlerExceptionResolver : Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Can not construct instance of com.matrix.domain.ui.IVehicle: abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of com.matrix.domain.ui.IVehicle: abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information at [Source: java.io.PushbackInputStream@5c46d800; line: 1, column: 1]

请指导我如何访问 JSON 对象 $scope.vehicle 作为 Rest Controller 中的接口(interface),我将非常感谢你。

谢谢

最佳答案

假设您的 IVehicle 接口(interface)可以用一个类来表示,也就是说,该类具有 IVehicle 接口(interface)的所有属性。我们将其命名为 MyVehicle

将以下内容添加到您的界面:

@JsonDeserialize(as = MyVehicle.class)
public interface IVehicle

关于java - Spring Rest Controller @RequestBody 用于除类之外的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49006868/

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