我有两个 POJO 类。
类 1 是 Engine.java:
private String engineId;
public String getEngineId(){
return this.engineId;
}
public void setEngineId(String engineId){
this.engineId = engineId;
}
第二个 POJO 类是 Vehicle.java:
private String type;
private String manufacturer;
private Engine engine;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public Engine getEngine() {
return engine;
}
public void setEngine(Engine engine) {
this.engine = engine;
}
我有一个 REST Controller ,用于提供车辆信息(RequestMethod.GET):
@RequestMapping(method = RequestMethod.GET)
public Vehicle getVechileDetails(Vehicle inputVehicle){
Vehicle vehicle = new Vehicle();
// some processing
return vehicle;
}
当我点击此服务并提供请求参数作为类型或制造商时,Spring 将创建车辆对象并填充类型和制造商的值。但是如果我提供了engineId的值,那么Spring就无法创建Engine对象,使得vehicle.getEngine().getEngineId() != null
如果我调用我的休息服务,有什么方法可以使用吗:
http://localhost:8080/Controller/getVehicleDetails?engineId=12345
然后使用具有engineId值的Engine创建车辆?
最佳答案
您可以这样获取vehicleId(包含ResponseEntity结构):
@RequestMapping(value = "/Controller/getVehicleDetails", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public
@ResponseBody
ResponseEntity<AjaxResponse> controller(@RequestParam(value = "engineId") Long engineId) {
//Do whatever you want with the engineId
return new ResponseEntity<AjaxResponse>(new AjaxResponse("Success"), HttpStatus.OK);
}
但是,对于 POJO,我必须警告两件事:
- 确保您的类实现
可序列化
- 对于从 Java 到 Javascript 转换时不确定的字段(反之亦然),例如
Date
变量,您必须正确设置 JsonSerializer 类
更新:您想从请求中获取对象,因此:
@RequestMapping(value = "/Controller/getVehicleDetails", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, , consumes = MediaType.APPLICATION_JSON_VALUE)
public
@ResponseBody
ResponseEntity<AjaxResponse> controller(@RequestBody Vehicle vehicle) {
//vehicle.getEngine().getEngineId()
return new ResponseEntity<AjaxResponse>(new AjaxResponse("Success"), HttpStatus.OK);
}
POJOS:
public class Engine implements Serializable {
//...
}
public class Vehicle implements Serializable {
private Engine engine;
}
JS端:
var vehicle = {
engine: {id: 123}//,
//...
}
//via angularjs:
$http.post("http://localhost:8080/Controller/getVehicleDetails", vehicle).success(function(response) {
console.log("success");
});
关于java - 将请求参数转换为Class对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42063318/