如何将 JSON 数组字段传递给 Spring REST 控制器

How to pass a JSON array field to a Spring REST Controller

我有一个 Dropdown multi selectbox to select 0..N 声明我正在传递给 Spring REST 控制器。在 JQuery 中,JSON 看起来像这样:{"states":["California","Vermont"]}。当我试图在控制器中获取这些值时,我只有 1 个州:states[]/California。此外,states[] 括号让我觉得我遗漏了一些东西,因为它看起来像一个数组名称,但控制器需要一个 Map。有什么想法吗?

$(document).ready(function() { 
   $('select').change(function() {         
        var states = { states: $("#cstates").val()};     
        alert(JSON.stringify(states));
        $.ajax({
          type: "POST",
          url: "http://localhost:8080/api/campaign/stats",
          data: states,
          cache: false,
          success: function(data){
             $("#resultarea").text(data);
          }
        });

   }); 
});

这是 REST 控制器代码:

@Slf4j
@RestController
public class CampaignStatsRESTController {

    @Autowired
    JdbcTemplate jdbcTemplate;

    @PostMapping("/api/campaign/stats")
    public List<String> getSearchResultViaAjax(@RequestParam Map<String,String> allParams) {

        //All SQL query parameters
        for (Map.Entry<String, String> entry : allParams.entrySet()) {
            log.info(entry.getKey() + "/" + entry.getValue());
        }
        //Send query -- TO DO : Add parameters      
        return jdbcTemplate.query("select count(*) as cnt from [dbo].[LineOfBusiness1CampaignTempOutput]", (rs, rowNum) -> rs.getString("cnt"));                   
    }   
}

更新 2: 按照建议:

    @PostMapping(path = "/api/campaign/stats",consumes = "application/json")
public List<String> getSearchResultViaAjax(@RequestBody Map<String, List<String>> allParams) {

然后我在 AJAX 调用中使用了数据类型和内容类型

 $(document).ready(function() { 
   $('select').change(function() {       
        //var formData = JSON.stringify($("#cstates").serializeArray());
        var states = { states : $("#cstates").val(), zips : $("#czips").val()};

        //alert(JSON.stringify(states));
        $.ajax({
          type: "POST",
          url: "http://localhost:8080/api/campaign/stats",
          data: JSON.stringify(states),
          cache: false,
          success: function(data){
             $("#resultarea").text(data);
          },
          dataType: "json",
          contentType : "application/json"
        });

   }); 
});

Map<String, String> 不是您需要的。您的结构可以用 Map<String, List<String>> 来描述,不幸的是,它在 Spring 中不起作用:(

如果您想将此信息作为查询参数传递,并且键 'states' 是静态的,最好的选择是:

@PostMapping("/api/campaign/stats")
public List<String> getSearchResultViaAjax(@RequestParam List<String> states) {

并查询:

 /api/campaign/stats?states=California,Vermont

如果 'states' 键是动态的,我会在请求正文中传递它:

@PostMapping("/api/campaign/stats")
public List<String> getSearchResultViaAjax(@RequestBody Map<String, List<String>> allParams) {