Sameervb
Sameervb

Reputation: 421

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. I'm not able to correctly pass a POST body to the API I've created. Any idea what might be going wrong ?

Below is my code :

Controller Class Method : // Main controller Class which is called from the REST API. Just the POST method for now.

@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:

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.

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

Upvotes: 1

Views: 18383

Answers (2)

Vitaly
Vitaly

Reputation: 115

You should create json like this:

{
"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:

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

Upvotes: 2

Simon Martinelli
Simon Martinelli

Reputation: 36223

You cannot use @RequestBody twice!

You should create a class that holds the two lists and use that class with @RequestBody

Upvotes: 3

Related Questions