如何将对象列表传递给Rest API POST方法?

时间:2019-06-05 14:37:14

标签: java json spring-boot post

我正在创建一个Spring Boot REST API,该API应该包含2个自定义对象列表。我无法正确将POST正文传递给我创建的API。任何想法可能出什么问题吗?

下面是我的代码:

控制器类方法: //从REST API调用的主控制器类。现在只是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,它将在数组中包含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
}

功能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());
    }
}

2 个答案:

答案 0 :(得分:0)

您不能两次使用@RequestBody

您应该创建一个包含两个列表的类,并将该类与@RequestBody一起使用

答案 1 :(得分:0)

您应该这样创建json:

{
"inputPlans":[],
"inputFeatures":[]
}

并创建这样的Class:

public class SolutionRequestBody {
    private List<Plan> inputPlans;
    private List<Feature> inputFeatures;

    //setters and getters
}

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);
    }