簡體   English   中英

如何將對象列表傳遞給Rest API POST方法?

[英]How do I pass list of objects to Rest API POST Method?

我正在創建一個Spring引導REST 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());
    }
}

你不能兩次使用@RequestBody

您應該創建一個包含兩個列表的類,並將該類與@RequestBody

你應該像這樣創建json:

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

並像這樣創建類:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM