如何将Ason的Json数组发送到Spring Controller?

时间:2019-03-03 19:31:10

标签: javascript json ajax spring spring-boot

我有一个如下所示的html表,将从中将数据转换为json形式,并通过ajax发送到spring控制器。在spring控制器中,我使用from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', include('blog.urls')), path('admin/', admin.site.urls), path('ckeditor', include('ckeditor_uploader.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) 来获取值,但是我将整个json字符串作为唯一键。使用modelAttribute可以实现这一点,但是我有不同的方案,因此我无法使用模型类,因此我还希望这些列标题及其值。

@RequestParam Map<String, String>

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

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

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"
   }
  ]

Spring控制器代码-

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

我想将json数据映射到 @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"); } ,如何实现呢?

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

map<string,string>

1 个答案:

答案 0 :(得分:3)

更改:

@RequestParam Map<String, String> attributeMap

收件人

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

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