【问题标题】:How to send Json array from ajax to spring Controller?如何将 Json 数组从 ajax 发送到 Spring Controller?
【发布时间】:2019-07-25 03:38:02
【问题描述】:

我有一个如下所示的 html 表,我将数据转换为 json 表单并通过 ajax 发送到 spring 控制器。在 spring 控制器中,我使用@RequestParam Map<String, String> 来获取值,但我将整个 json 字符串作为唯一的键。使用 modelAttribute 我可以实现这一点,但我有不同的场景,所以我不能使用模型类,所以我也想要这些列标题及其值。

<table>
<thead>
<tr>
    <th>Column 1</th>
    <th>Column 2</th>
    <th>Column 3</th>
</tr>
</thead>
<tbody>
<tr>
    <td>A1</td>
    <td>A2</td>
    <td></td>
</tr>
<tr>
    <td>B1</td>
    <td>B2</td>
    <td>B3</td>
</tr>
<tr>
    <td>C1</td>
    <td></td>
    <td>C3</td>
</tr>
</tbody>

我将 html 表数据转换为 json 并通过 ajax 发送。 -

  [
    {
    "Column 1": "A1",
    "Column 2": "A2",
    "Column 3": ""
    },
   {
    "Column 1": "B1",
    "Column 2": "B2",
    "Column 3": "B3"
   },
   {
    "Column 1": "C1",
    "Column 2": "",
    "Column 3": "C3"
   }
  ]

ajax 代码 -

$.ajax({
        type: "POST",
        //contentType : 'application/json; charset=utf-8',
        //dataType : 'json',
        url: "/gDirecotry/" + id,
        data: JSON.stringify(rows),
        success: function (result) {
            console.log(result);
        }
    });

弹簧控制器代码 -

  @RequestMapping(value = "/gDirecotry/{id}", method = RequestMethod.POST)
  public @ResponseBody ModelAndView 
      getSearchUserProfiles(@PathVariable("id") String id,
                                 @RequestParam Map<String, String> 
   attributeMap) throws IOException {

return new ModelAndView("redirect:/home");
  }

我想将 json 数据映射到map&lt;string,string&gt;,我怎么能做到这一点?

输出:- 我把这整个字符串作为唯一没有价值的键。

[{"Column 1":"A1","Column 2":"A2","Column 3":""},{"Column 1":"B1","Column 
2":"B2","Column 3":"B3"},{"Column 1":"C1","Column 2":"","Column 3":"C3"}]

【问题讨论】:

    标签: javascript json ajax spring spring-boot


    【解决方案1】:

    变化:

    @RequestParam Map<String, String> attributeMap
    

    @RequestBody List<Map<String, String>> attributeMap
    

    您的JSON 有效负载是一个对象数组。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-15
    • 1970-01-01
    • 2015-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-24
    • 1970-01-01
    相关资源
    最近更新 更多