【问题标题】:How do I pass list of objects to Rest API POST Method?如何将对象列表传递给 Rest API POST 方法?
【发布时间】:2019-10-21 02:17:45
【问题描述】:

我正在创建一个 Spring boot 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 ,这将包含一个数组中的要素类对象:

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

【问题讨论】:

    标签: java json spring-boot post


    【解决方案1】:

    你不能使用@RequestBody 两次!

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

    【讨论】:

      【解决方案2】:

      你应该像这样创建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);
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-04-03
        • 2017-03-07
        • 2013-12-12
        • 1970-01-01
        • 1970-01-01
        • 2023-03-03
        • 2018-05-12
        • 1970-01-01
        相关资源
        最近更新 更多