简体   繁体   中英

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

I have a Dropdown multi selectbox to select 0..N states that I am passing to a Spring REST controller. In JQuery, the JSON looks like this : {"states":["California","Vermont"]}. When I am trying to get these values in the controller, I have only 1 state : states[]/California. Also, the states[] brackets makes me think I am missing something because that looks like an array name but the controller is expecting a Map. Any ideas ?

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

   }); 
});

Here is the REST controller code:

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

UPDATE 2 : As suggested :

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

Then I have use Data type and content type in the AJAX call

 $(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> is not what you need. Your structure could be described rather by Map<String, List<String>> , unfortunately, it does not work in Spring :(

If you want to pass this info as a query parameter, and key 'states' is static, the best choice would be:

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

and query:

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

If 'states' key is dynamic, I would pass it in request body:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM