[英]How do I pass list of objects to Rest API POST Method?
I'm creating a Spring boot REST API which should take 2 Lists of custom objects. 我正在创建一个Spring引导REST API,它应该包含2个自定义对象列表。 I'm not able to correctly pass a POST body to the API I've created. 我无法正确地将POST主体传递给我创建的API。 Any idea what might be going wrong ? 知道可能出了什么问题吗?
Below is my code : 以下是我的代码:
Controller Class Method : // Main controller Class which is called from the REST API. 控制器类方法://主控制器从REST API调用的类。 Just the POST method for now. 现在只是POST方法。
@RequestMapping(value = "/question1/solution/", method = RequestMethod.POST)
public List<Plan> returnSolution(@RequestBody List<Plan> inputPlans, @RequestBody List<Feature> inputFeatures) {
logger.info("Plans received from user are : " + inputPlans.toString());
return planService.findBestPlan(inputPlans, inputFeatures);
}
Plan Class , this will contain the Feature class objects in an array: Plan Class,它将包含数组中的Feature类对象:
public class Plan {
public Plan(String planName, double planCost, Feature[] features) {
this.planName = planName;
this.planCost = planCost;
this.features = features;
}
public Plan() {
}
private String planName;
private double planCost;
Feature[] features;
public String getPlanName() {
return planName;
}
// getters & setters
}
Feature POJO Class : // Feature will contain features like - email , archive etc. 功能POJO类://功能将包含诸如电子邮件,存档等功能。
public class Feature implements Comparable<Feature> {
public Feature(String featureName) {
this.featureName = featureName;
}
public Feature() {
}
private String featureName;
// Getters / Setters
@Override
public int compareTo(Feature inputFeature) {
return this.featureName.compareTo(inputFeature.getFeatureName());
}
}
You cannot use @RequestBody
twice! 你不能两次使用@RequestBody
!
You should create a class that holds the two lists and use that class with @RequestBody
您应该创建一个包含两个列表的类,并将该类与@RequestBody
You should create json like this: 你应该像这样创建json:
{
"inputPlans":[],
"inputFeatures":[]
}
and create Class like this: 并像这样创建类:
public class SolutionRequestBody {
private List<Plan> inputPlans;
private List<Feature> inputFeatures;
//setters and getters
}
POST mapping like this: POST映射如下:
@RequestMapping(value = "/question1/solution/", method = RequestMethod.POST)
public List<Plan> returnSolution(@RequestBody SolutionRequestBody solution) {
logger.info("Plans received from user are : " + solution.getInputPlans().toString());
return planService.findBestPlan(solution);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.